VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-check-if-string-contains-only-digits-in-java/

⇱ How to Check if a String Contains only Digits in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Check if a String Contains only Digits in Java?

Last Updated : 15 Jul, 2025

In Java, to check if a string contains only digits, we can use various methods such as simple iteration, regular expressions, streams, etc.

Example:

The example below uses the Character.isDigit() method to check each character of the string to ensure all characters are digits. This is the most simple method among all others.


Output
true
false

Other Methods to Check if a String Contains only Digits

1. Using Regular Expressions

In this method, we will use the regular expressions to check if the string matches the pattern of only digits. This method is more complex than Character.isDigit() but still very readable and concise.

Explanation: In the above example, the regular expression "[0-9]+" matches strings that contain only digits. The matches() method returns true if the string matches the regex.

2. Using Traversal

In this method, the idea is to traverse each character in the string and check if the character of the string contains only digits from 0 to 9. If all the character of the string contains only digits then return true, otherwise, return false.


Output
false

Note: This approach works but is less readable than Character.isDigit(), as it requires checking ASCII values manually.

3. Using Arraylist.contains() Method

In this method, it creates an ArrayList of digits (0 to 9) and checks if each character in the string is present in this list. It is less efficient and more complex than other methods.


Output
true
Comment