English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/)

Java Reader/Writer

Java Other Topics

Java program to check if a string is a number

Comprehensive Java Examples

In this program, you will learn different methods to check if a string is a number in Java.

Example1Check if a string is a number

public class Numeric {
    public static void main(String[] args) {
        String string = "}}12345.15";
        boolean numeric = true;
        try {
            Double num = Double.parseDouble(string);
        }
            numeric = false;
        }
        if(numeric)
            System.out.println(string + "		Is a number");
        else
            System.out.println(string + "		Not a number");
    }
}

When running the program, the output is:

12345.15 is a number

In the above program, we have a string named string (String) that contains the string to be checked. We also have a boolean value numeric that stores the final result of whether it is a numeric value.

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

If an error is thrown (i.e., NumberFormatException), it means that the string is not a number, and numeric is set to false. Otherwise, it indicates that this is a number.

However, if you need to check multiple strings, you should convert it to a function. And, the logic is based on throwing exceptions, which can be very costly.

Alternatively, we can use the functionality of regular expressions to check if a string is a number, as shown below.

Example2Check if a string is a number 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 + "		Not a number");
    }
}

When running the program, the output is:

-1234.15 is a number

In the above program, we use regex to check if the string is a number, rather than using try-catch block. This is done using the String's matches() method.

in the matches() method

  • -? Allows zero or more-for negative numbers in the string.

  • \\d+ Check if the string has at least1or more numbers (\\d).

  • (\\..\\d+)? Allows zero or more of the given pattern (\\..\\d+) among

    • \\.. Check if the string contains a dot (decimal point)

    • If so, it should at least follow one or more numbers \\d+.

Comprehensive Java Examples