Check if a String contains only digits in Java

In this post, you will learn to check if a String contains only digits in Java.

We will cover two methods:

  • Using the Character.isDigit() method
  • Using the Integer.parseInt() method

Check if a String contains only digits in Java using the Character.isDigit() method

In this example, we use a for loop to iterate over the elements (chars) of the String. For each iteration, we pass the current char to the isDigit() method of the Character class, which is a wrapper class in Java for the primitive datatype char. The isDigit() method checks whether the provided char is a digit and returns true if it is, otherwise it returns false.

Example

class Test {

  public static void main(String[] args) {
    String str = "129843875";
    boolean containsOnlyDigits = true;

    for (int i = 0; i < str.length(); i++) {
      if (!Character.isDigit(str.charAt(i))) { // in case that a char is NOT a digit, enter to the if code block
        containsOnlyDigits = false;
        break; // break the loop, since we found that this char is not a digit
      }
    }

    if (containsOnlyDigits) {
      System.out.println("String contains only digits!");
    } else {
      System.out.println("String does not contain only digits!");
    }
  }
}
Output: String contains only digits!

Check for digits in a String using the Integer.parseInt() method

There is an easy way to determine if a String contains only digits without iterating over its chars.  We can do that by passing the String as an argument to the parseInt() method from the Integer class. This method throws a NumberFormatException if the String does not contain a parsable integer.

Example

class Test {

  public static void main(String[] args) {
    String str1 = "129843875";
    String str2 = "1234B";

    try {
      Integer.parseInt(str1);
      System.out.println("str1 contains only digits.");
    } catch (NumberFormatException nfe) {
      System.out.println("str1 does not contains only digits!");
    }

    try {
      Integer.parseInt(str2);
      System.out.println("str2 contains only digits.");
    } catch (NumberFormatException nfe) {
      System.out.println("str2 does not contains only digits!");
    }
  }
}
Output: str1 contains only digits. str2 does not contain only digits!
 
Here, if we get an exception in the try block, the catch block will be executed, which means that the provided string does not contain only numbers.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *