ebruchez ebruchez - 1 month ago 4
Java Question

How can I efficiently (without throwing exceptions for invalid input) parse an integer in Java?

This question is a follow-up to Does java have a int.tryparse that doesn't throw an exception for bad data?, which is marked as a duplicate of Java: Good way to encapsulate Integer.parseInt().

Both questions seem to be more about how to catch the

thrown by
or provide a better API which does not use exceptions by encapsulating

But neither is formulated to specifically address the performance aspect of the fact that Java's
throws an exception if the input is not parseable as an
. If most of your input consists of valid
s, this won't matter. But if your input consists of a lot of data which may or may not be
s and you need to parse it,
will be inefficient.

So this specific question is about how to parse integers efficiently, given that the input can consists of lots of valid integers but also lots of invalid ones.


The best answer I have found so far without writing my own integer parsing code or using flaky regexes is to use Guava's Ints.tryParse(String string) or Longs.tryParse(String string, int radix) method.

Longs.tryParse() is basically a reimplementation of the standard Java Long.parseLong(), but returning null or a Long instead of throwing a NumberFormatException. This seems to me to be the best approach: it is as efficient at parsing as Long.parseLong() but handles the error case more efficiently.