How would you check if a String was a number before parsing it?
Google's Guava library provides a nice helper method to do this: Ints.tryParse
. You use it like Integer.parseInt
but it returns null
rather than throw an Exception if the string does not parse to a valid integer. Note that it returns Integer, not int, so you have to convert/autobox it back to int.
Example:
String s1 = "22";
String s2 = "22.2";
Integer oInt1 = Ints.tryParse(s1);
Integer oInt2 = Ints.tryParse(s2);
int i1 = -1;
if (oInt1 != null) {
i1 = oInt1.intValue();
}
int i2 = -1;
if (oInt2 != null) {
i2 = oInt2.intValue();
}
System.out.println(i1); // prints 22
System.out.println(i2); // prints -1
However, as of the current release -- Guava r11 -- it is still marked @Beta.
I haven't benchmarked it. Looking at the source code there is some overhead from a lot of sanity checking but in the end they use Character.digit(string.charAt(idx))
, similar, but slightly different from, the answer from @Ibrahim above. There is no exception handling overhead under the covers in their implementation.