Write a Java Program to Check if a String is Numeric

In Java, you can check whether a given string is a numeric or not by using the built-in methods of the String and Number classes.

Here is a simple program to demonstrate how to check whether a string is numeric or not:

public class NumericCheck {
    public static boolean isNumeric(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        String str = "123.45";
        if (isNumeric(str)) {
            System.out.println(str + " is a numeric string.");
        } else {
            System.out.println(str + " is not a numeric string.");
        }
    }
}

In the above program, the isNumeric method takes a string as input and tries to parse it as a double using the Double.parseDouble method.

If the parsing is successful, it returns true, indicating that the string is numeric.

Otherwise, it catches the NumberFormatException and returns false.

In the main method, we pass a string str to the isNumeric method and print a message indicating whether it is numeric or not.

You can test this program with different input strings to see how it works.

Here are some examples:

String str1 = "123";
String str2 = "123.45";
String str3 = "abc";

System.out.println(isNumeric(str1)); // Output: true
System.out.println(isNumeric(str2)); // Output: true
System.out.println(isNumeric(str3)); // Output: false

In summary, checking whether a string is numeric in Java is easy with the Double.parseDouble method and the NumberFormatException exception.

By using this simple program, you can quickly determine if a string is numeric or not.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.