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!"); }
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!"); } } }
String contains only digits!
Let us see another example.
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!"); } } }
String: 5demo9 String contains digits as well as other characters!