Check whether the String contains only digit characters in Java

Java 8Object Oriented ProgrammingProgramming

The following is our string.

String str = "4434";

To check whether the above string has only digit characters, try the following if condition that uses matches() method and checks for every character.

if(str.matches("[0-9]+") && str.length() > 2) {
System.out.println("String contains only digits!");
}

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "4434";
      if(str.matches("[0-9]+") && str.length() > 2) {
         System.out.println("String contains only digits!");
      }
   }
}

Output

String contains only digits!

Let us see another example.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "5demo9";
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2) {
         System.out.println("String contains only digits!");
      } else {
         System.out.println("String contains digits as well as other characters!");
      }
   }
}

Output

String: 5demo9
String contains digits as well as other characters!
raja
Published on 14-Dec-2018 15:21:49
Advertisements