How to check if a string contains only digits in Java

To check if a string contains only digits in Java, you can use the matches() method of the String class in combination with the regular expression "\\d+". The matches() method returns true if the string matches the regular expression, and false if it does not.

Here is an example of how you can use the matches() method to check if a string contains only digits:

String str = "12345";
boolean isDigits = str.matches("\\d+");  // isDigits is true

The regular expression "\\d+" matches one or more digits (\\d), so the string must contain only digits to be considered a match.

Alternatively, you can use the CharSequence.chars() method and the Character.isDigit() method to check if each character in the string is a digit:

String str = "12345";
boolean isDigits = str.chars().allMatch(Character::isDigit);  // isDigits is true

Keep in mind that both approaches will treat an empty string as containing only digits. If you want to treat an empty string as not containing only digits, you can add an additional check for an empty string.

For example:

String str = "12345";
boolean isDigits = !str.isEmpty() && str.matches("\\d+");  // isDigits is true
String str = "12345";
boolean isDigits = !str.isEmpty() && str.chars().allMatch(Character::isDigit);  // isDigits is true