How to Check If a String is Integer
There are a few ways to check if a string is integer or not.Here I will try to implement some of these methods.
First one is using regular expressions and this is the one I use mostly.This matches as
-? –> negative sign, could have none or one
\d+ –> one or more digits
Using parseInt is possible as well.In this way you should try to parse a String to integer and catch if any exceptions occur. If your code creats an NumberFormatException then you should return false.We don’t care about other exceptions here.If there is no exception that means it went okey and your string is indeed an integer. Also please be aware that we used parseInt() and not the Integer.valueOf() method.You can check the differences here.
Another way is more complex but much faster than Integer.parseInt() or regex method.It’s better to check which works best for you. Here some of you may ask why not use java.lang.Character.isDigit() and check the char values itself.isDigit returns true for things like Devanagari digits. While Integer.parseInt() handles these as digits, it may not be what’s expected for most use cases
The last one is using StringUtils or NumberUtils which is not a good idea but it works.You can check the detailed page here.
Which one is the best to use?If you need performance you should use the Jonas one.It may look unnecessary but it is really fast. Here some test results with these methods.Running many times these methods shows that it may differ a lot.