Java Program to validate if a String contains only numbers

Java 8Object Oriented ProgrammingProgramming

To validate if a String has only numbers, you can try the following codes. We have used the matches() method in Java here to check for number in a string.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "978";
      System.out.println("Checking for string that has only numbers...");
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2)
      System.out.println("String has only numbers!");
      else
      System.out.println("String consist of characters as well!");
   }
}

Output

Checking for string that has only numbers...
String: 978
String has only numbers!

Let us see another example, wherein our string has numbers as well as characters.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "s987jyg";
      System.out.println("Checking for string that has only numbers...");
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2)
      System.out.println("String has only numbers!");
      else
      System.out.println("String consist of characters as well!");
   }
}

Output

Checking for string that has only numbers...
String: s987jyg
String consist of characters as well!
raja
Published on 13-Nov-2018 10:05:03
Advertisements