Check whether the String contains only digit characters in Java


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!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

877 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements