Determine if a String is a valid number or not in Java

In this post, we will explore several ways to determine if a String is a valid number or not. 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 function for this simple task. Nevertheless, there are several methods to check if the given String is numeric in Java –

 

1. Custom method

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

 

Download   Run Code

Output:

IsNumeric: true

 

2. Lambda expressions:

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

 

Download   Run Code

Output:

IsNumeric: true

 

3. Regular Expression

We can use the regular expression "[0-9]+" or "\\d+" which checks if a String is numeric. This can be done using matches() method of String class which tells whether or not 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. 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()

 

 

 

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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of