As an alternative approach to trying to parse the string and catching NumberFormatException
, you could use a regex; e.g.
if (Pattern.compile("-?[0-9]+").matches(str)) {
// its an integer
}
This is likely to be faster, especially if you precompile and reuse the regex.
However, the problem with this approach is that Integer.parseInt(str)
will also fail if str
represents a number that is outside range of legal int
values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT
to Integer.MAX_INT
, it is not a pretty sight. (And I am not going to try it ...)
On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.