This post will explore several ways to determine whether a string is a valid number in Java. The solution checks if a string contains only Unicode digits and doesn’t allow either positive or negative leading sign or a decimal point. A null string or an empty string should return false.

Java did not provide any standard method for this simple task. Nevertheless, there are several methods to check if the given string is numeric in Java:

1. Custom method

A simple solution is to write our own utility method for this simple task. The idea is to iterate over string characters and check each character to be numeric using Character.isDigit(char). This is demonstrated below:

Download  Run Code

Output:

IsNumeric: true

2. Using Lambda Expressions

From Java 8 onwards, this can be efficiently done using lambda expressions:

Download  Run Code

Output:

IsNumeric: true

3. Using Regular Expression

We can use the regular expression "[0-9]+" or "\\d+" which checks if a string is numeric. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.

Download  Run Code

Output:

IsNumeric: true

 
If the regular expression is frequently called, we should compile it first for performance boost:

Download  Run Code

Output:

IsNumeric: true

4. Using Apache Commons Lang

We can also use Apache Commons Lang library, which provides several methods to check for a numeric string:

1. StringUtils#isNumeric()
2. NumberUtils#isCreatable()
3. NumberUtils#isNumber()

Download Code

5. Using Wrapper classes built-in methods

The idea is to parse a string by Integer.parseInt() or Long.parseLong(), which generates a NumberFormatException for non-numeric strings. Notice that this method fails when the value is outside the range for int or long, respectively.

Download  Run Code

Output:

IsNumeric: true

That’s all about checking if a String is a valid number or not in Java.