Join our newsletter for the latest updates.
Java Program to Check if a String is Numeric

Java Program to Check if a String is Numeric

In this program, you'll learn different techniques to check if a string is numeric or not in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Check if a string is numeric

public class Numeric {

    public static void main(String[] args) {

        String string = "12345.15";
        boolean numeric = true;

        try {
            Double num = Double.parseDouble(string);
        } catch (NumberFormatException e) {
            numeric = false;
        }

        if(numeric)
            System.out.println(string + " is a number");
        else
            System.out.println(string + " is not a number");
    }
}

Output

12345.15 is a number

In the above program, we have a String named string that contains the string to be checked. We also have a boolean value numeric which stores if the final result is numeric or not.

To check if the string contains numbers only, in the try block, we use Double's parseDouble() method to convert the string to a Double.

If it throws an error (i.e. NumberFormatException error), it means the string isn't a number and numeric is set to false. Else, it's a number.

However, if you want to check if for a number of strings, you would need to change it to a function. And, the logic is based on throwing exceptions, this can be pretty expensive.

Instead, we can use the power of regular expressions to check if the string is numeric or not as shown below.


Example 2: Check if a string is numeric or not using regular expressions (regex)

public class Numeric {

    public static void main(String[] args) {

        String string = "-1234.15";
        boolean numeric = true;

        numeric = string.matches("-?\\d+(\\.\\d+)?");

        if(numeric)
            System.out.println(string + " is a number");
        else
            System.out.println(string + " is not a number");
    }
}

Output

-1234.15 is a number

In the above program, instead of using a try-catch block, we use regex to check if string is numeric or not. This is done using String's matches() method.

In the matches() method,

  • -? allows zero or more - for negative numbers in the string.
  • \\d+ checks the string must have at least 1 or more numbers (\\d).
  • (\\.\\d+)? allows zero or more of the given pattern (\\.\\d+) in which
    • \\. checks if the string contains . (decimal points) or not
    • If yes, it should be followed by at least one or more number \\d+.