OneBite.Dev - Coding blog in a bite size

check if a string contains only numbers in java

Code snippet on how to check if a string contains only numbers in java

  public static boolean isNumeric(String str) {
    try {
        double d = Double.parseDouble(str);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

This is a Java function that checks if a string contains only numbers. The function is called isNumeric and takes in one parameter, a String object named str. Firstly, the code attempts to convert the string to a double data type using the Double.parseDouble() method. If this is successful, the code will return true. Otherwise, if the conversion fails, a NumberFormatException will be thrown and the function will return false, indicating that the string does not contain only numbers.

java