Google News
logo
Java Program to Check if a String is Numeric
In the following example of Java program to check if a string is numeric :
Program :
public class NumericStringCheck {
    public static void main(String[] args) {
        String str1 = "1234";
        String str2 = "-1234.56";
        String str3 = "abc123";
        String str4 = "12.34.56";
        System.out.println(str1 + " is numeric: " + isNumeric(str1));
        System.out.println(str2 + " is numeric: " + isNumeric(str2));
        System.out.println(str3 + " is numeric: " + isNumeric(str3));
        System.out.println(str4 + " is numeric: " + isNumeric(str4));
    }
    
    public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
Output :
1234 is numeric: true
-1234.56 is numeric: true
abc123 is numeric: false12.34.56 is numeric: false
We define four strings str1, str2, str3, and str4 to test the isNumeric() method. We then call the isNumeric() method for each of these strings and print the result to the console.

The isNumeric() method takes a string str as input and attempts to parse it as a double. If the parsing is successful, it returns true, indicating that the string is numeric. Otherwise, it catches the NumberFormatException that is thrown and returns false, indicating that the string is not numeric.