Java – Check if String contains only Digits

To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if the characters in the given string are digits.

String.matches() with argument as "[0-9]+" returns a boolean value of true if the String contains only digits, else it returns false.

The syntax to use a String.matches() to check if String contains only digits is

</>
Copy
String.matches("[0-9]+")

Example – Positive Scenario

In the following program, we will take a string and check if it contains only digits using String.matches() method.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		String str = "5236841234";
		boolean result = str.matches("[0-9]+");
		System.out.println("Original String : " + str);
		System.out.println("Does string contain only Digits? : " + result);
	}
}

Output

Original String : 5236841234
Does string contain only Digits? : true

Example – Negative Scenario

In the following program, we will take a string containing some alphabets and whitespace characters. When we check if this String contains only digits using String.matches() method, we should get false as return value.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		String str = "ABCD 1234";
		boolean result = str.matches("[0-9]+");
		System.out.println("Original String : " + str);
		System.out.println("Does string contain only Digits? : " + result);
	}
}

Output

Original String : ABCD 1234
Does string contain only Digits? : false

Conclusion

In this Java Tutorial, we learned how to check if given String contains only digits, using String.matches() method.