- How to check if a String is numeric in Java? Use isNumeric() or isNumber() Example
- Using Apache Commons StringUtils.isNumeric() to check if String is valid number
- Java: Check if String is a Number
- Check if String is Numeric with Core Java
- Check if String is Numeric with Apache Commons
- NumberUtils.isParsable()
- Free eBook: Git Essentials
- NumberUtils.isCreatable()
- NumberUtils.isDigits()
- StringUtils.isNumeric()
- StringUtils.isNumericSpace()
- Check if String is Numeric with Regex
- Conclusion
How to check if a String is numeric in Java? Use isNumeric() or isNumber() Example
In day-to-day programming, you often need to check if a given string is numeric or not. It’s also a good interview question but that’s a separate topic of discussion. Even though you can use Regular expression to check if the given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third-party libraries like Apache commons-lang will handle e.g. hexadecimal and octal String. Hence, In the Java application, the simplest way to determine if a String is a number or not is by using the Apache Commons lang’s isNumber() method, which checks whether the String is a valid number in Java or not.
Valid numbers include hexadecimal marked with the 0x or 0X qualifier, octal numbers, scientific notation, and numbers marked with a type qualifier (e.g. 123L). Non-hexadecimal strings beginning with a leading zero are treated as octal values.
Thus the string 09 will return false since 9 is not a valid octal value. However, numbers beginning with 0. are treated as decimal.null and empty/blank String will return false .
Another way to check if String is numeric or not is by using the isNumeric() method of StringUtils class from the same library. This method also has rules to determine valid numbers e.g. it checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
Similarly, this method will return false for null and empty String. It also does not allow for a leading sign, either positive or negative. Also, if a String passes the numeric test, it may still generate a NumberFormatException when parsed by Integer.parseInt() or Long.parseLong() , e.g. if the value is outside the range of int or long respectively.
Using Apache Commons StringUtils.isNumeric() to check if String is valid number
Here are a couple of examples for different input to check if String is a valid number or not, this will give you a good idea of how this method work and what you can expect from this method.
StringUtils.isNumeric(null) = false StringUtils.isNumeric("") = false StringUtils.isNumeric(" ") = false StringUtils.isNumeric("123") = true StringUtils.isNumeric("ab2c") = false StringUtils.isNumeric("-123") = false StringUtils.isNumeric("+123") = false StringUtils.isNumeric("12 3") = false StringUtils.isNumeric("12-3") = false StringUtils.isNumeric("12.3") = false
Just note there are a couple of interesting changes in Apache commons-lang 2.5 and 3.0, the 3.0 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence). The Apache commons-lang 3.0 also changed empty String » » to return false and not true , which is a very important change.
Now, let’s use the isNumber() method to check if String is a valid number or not
NumberUtils.isNumber(null) = false NumberUtils.isNumber("") = false NumberUtils.isNumber(" ") = false NumberUtils.isNumber("123") = true NumberUtils.isNumber("ab2c") = false NumberUtils.isNumber("-123") = true NumberUtils.isNumber("+123") = false NumberUtils.isNumber("12 3") = false NumberUtils.isNumber("12-3") = false NumberUtils.isNumber("12.3") = true
Since Apache commons-lang 3.3 this method also supports hex 0Xhhh and octal 0ddd validation. As I said before, you can also use a regular expression to check if the given String is empty or not but you need to be very careful about covering all scenarios covered by these libraries.
Personally, I would not recommend you reinvent the wheel. Even Joshua Bloch has advised in «Effective Java» that always prefer the library method to writing your own routine.
One of the main reasons for that is testing exposure, your own routing will not get the free testing by millions of programmers to which a library method is exposed.
That’s all about how to check if String is a valid number in Java or not. Though you can write your own routine in Java to find out whether a String is numeric or not, it will require you to handle a lot of special cases e.g. leading + or — sign, out-of-range integers, decimal points, octal or hexadecimal numbers, etc.
So if you don’t have your requirement locked down, it’s better not to reinvent the wheel and reuse the tried and tested code from the popular open-source libraries like Apache Commons lang. Even Josh Bloch advised about knowing and using library methods for better code.
- How to format a String in Java? (tutorial)
- How to parse String to float in Java? (tutorial)
- How to compare two String in Java? (tutorial)
- How to replace String in Java? (example)
- How to convert char to String in Java? (tutorial)
- How to add leading zeros to an Integer in Java? (tutorial)
- How to join String by a delimiter in Java 8? (tutorial)
- How to split String by delimeter in Java? (tutorial)
- How to concatenate String in Java? (example)
- How to split a String by whitespace or tabs in Java? (tutorial)
- How to convert String to Date in Java? (tutorial)
- When should you use the intern() method of String? (article)
Java: Check if String is a Number
Strings are a handy way of getting information across and getting input from a user.
In this article, we will go through a couple of ways check if a String is Numeric in Java — that is to say, if a String represents a numeric value.
Check if String is Numeric with Core Java
Users tend to mistype input values fairly often, which is why developers have to hold their hand as much as possible during IO operations.
The easiest way of checking if a String is a numeric or not is by using one of the following built-in Java methods:
- Integer.parseInt()
- Integer.valueOf()
- Double.parseDouble()
- Float.parseFloat()
- Long.parseLong()
These methods convert a given String into its numeric equivalent. If they can’t convert it, a NumberFormatException is thrown, indicating that the String wasn’t numeric.
It’s worth noting that Integer.valueOf() returns a new Integer() , while Integer.parseInt() returns a primitive int . Keep this in mind if such a difference would change the flow of your program.
String string = "10"; try < intValue = Integer.parseInt(string); return true; > catch (NumberFormatException e) < System.out.println("Input String cannot be parsed to Integer."); >
Now, we can abstract this functionality into a helper method for convenience:
public static boolean isNumeric(String string) < int intValue; System.out.println(String.format("Parsing string: \"%s\"", string)); if(string == null || string.equals("")) < System.out.println("String cannot be parsed, it is null or empty."); return false; > try < intValue = Integer.parseInt(string); return true; > catch (NumberFormatException e) < System.out.println("Input String cannot be parsed to Integer."); > return false; >
String string = "10"; if(isNumeric(string)) < System.out.println("String is numeric!"); // Do something > else < System.out.println("String is not numeric."); >
Running this code would result in:
Parsing string: "10" String is numeric!
On the other hand, if we expect the String to contain a really big number, then we can call the BigInteger(String) constructor, which translates the String representation into a BigInteger .
Check if String is Numeric with Apache Commons
Apache Commons is one of the most used third-party libraries for expanding the basic Java Framework. It gives us more fine control over core Java classes, in this case, Strings.
We’ll be looking at two classes from the Apache Commons library:
Both of which are very similar to their vanilla Java class counterparts, but with an emphasis on null-safe operations (on numbers and strings respectively), meaning we can even define default values for missing (null) values.
Let’s now take a look at how we can check for numeric values using these methods.
NumberUtils.isParsable()
This method accepts a String and checks if it’s a parsable number or not, we can be use this method instead of catching an exception when calling one of the methods we mentioned earlier.
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
This is very good because solutions that involve frequent exception handling should be avoided if possible — this is exactly what this method helps us with.
Note that hexadecimal numbers and scientific notations are not considered parsable.
Now, we don’t really even need a convenience helper method, as isParseable() returns a boolean itself:
String string = "10"; if (NumberUtils.isParsable(string)) < System.out.println("String is numeric!"); > else < System.out.println("String is not numeric."); >
NumberUtils.isCreatable()
This method also accepts a String and checks if it’s a valid Java number. With this method we can cover even more numbers, because a valid Java number includes even hexadecimal and octal numbers, scientific notation, as well as numbers marked with a type qualifier.
Now, we can even use something along the lines of:
String string = "0x10AB"; if (NumberUtils.isCreatable(string)) < System.out.println("String contains a creatable number!"); > else < System.out.println("String doesn't contain creatable number."); >
String contains a creatable number!
NumberUtils.isDigits()
The NumberUtils.isDigits() method checks if a string contains only Unicode digits. If the String contains a leading sign or decimal point the method will return false :
String string = "25"; if (NumberUtils.isDigits(string)) < System.out.println("String is numeric!"); > else < System.out.println("String isn't numeric."); >
StringUtils.isNumeric()
The StringUtils.isNumeric() is the StringUtils equivalent of NumberUtils.isDigits() .
If the String passes the numeric test, it may still generate a NumberFormatException error when parsed by the methods we mentioned earlier, for example if it is out of range for int or long .
Using this method we can determine if we can parse String into an Integer :
String string = "25"; if (StringUtils.isNumeric(string)) < System.out.println("String is numeric!"); > else < System.out.println("String isn't numeric."); >
StringUtils.isNumericSpace()
Additionally, if we expect to find more numbers within a String, we can use isNumericSpace , another useful StringUtils method worth mentioning. It checks if the String contains only Unicode digits or spaces.
Let’s check a String that contains numbers and spaces:
String string = "25 50 15"; if (StringUtils.isNumericSpace(string)) < System.out.println("String is numeric!"); > else < System.out.println("String isn't numeric."); >
Check if String is Numeric with Regex
Even though most developers will be content with using an already implemented method, sometimes you might have very specific pattern checking:
public static boolean isNumeric(String string) < // Checks if the provided string // is a numeric by applying a regular // expression on it. String regex = "4+[\\.]?1*"; return Pattern.matches(regex, string); >
And then, we can call this method:
System.out.println("123: " + isStringNumeric2("123")); System.out.println("I'm totally a numeric, trust me: " + isStringNumeric2("I'm totally a numeric, trust me"));
Running this gives us the following output:
123: true I'm totally a numeric, trust me: false
Conclusion
In this article, we’ve covered several ways to check if a String is numeric or not (represents a number) in Java.
We’ve started off using Core Java, and catching a NumberFormatException , after which we’ve used the Apache Commons library. From there, we’ve utilized the StringUtils and NumberUtils classes to check whether a String is numeric or not, with various formats.