How can I efficiently (without throwing exceptions for invalid input) parse an integer in Java?
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.
String to Int in java - Likely bad data, need to avoid exceptions
That's pretty much it, although returning MIN_VALUE is kind of questionable, unless you're sure it's the right thing to use for what you're essentially using as an error code. At the very least I'd document the error code behavior, though.
Might also be useful (depending on the application) to log the bad input so you can trace.
Way to parseInt without try-catch in Java 8?
Unlike other answers that are now deleted, I don't think this really has to do with Java being backwards-compatible.
Because an empty Optional
represents a value that is absent, it would mean that the method actually worked but no results are returned.
However, parsing hello
as an integer will not work and has to throw an exception, because it is an error rather than an empty result. Keep in mind that NumberFormatException
extends IllegalArgumentException
.
More generally speaking, Optional
was made for dealing with possibly absent values (instead of using null
for that), and not for error handling. Also, Optional
doesn't provide any way to know what is the error and why there is one.
Good way to encapsulate Integer.parseInt()
You could return an Integer
instead of an int
, returning null
on parse failure.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
EDIT: Code for such a method:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
Note that I'm not sure off the top of my head what this will do if text
is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
Originally this answer used the new Integer(String)
constructor; it now uses Integer.parseInt
and a boxing operation; in this way small values will end up being boxed to cached Integer
objects, making it more efficient in those situations.
What's the correct way to test if a user has entered a number which exceeds the size of the memory used to interpret that number?
When you get the userInput for the first time you should verify that what the user enters is valid and if it is, then Integer.parseInt() will work. If it's not valid, i.e. a value greater than Integer.MAX_VALUE, it will throw an exception.
The behavior you're describing leads to using the catch as flow control which is not a good design...
BAD:
try{
Integer.parseInt(max);
//do something with the integer
}catch (NumberFormatException e)
{
//user has entered too many digits for an Integer to hold.
userInput = Integer.MAX_VALUE + "";
}
To check is passed string parsable to Integer?
I would have used:
s = s.trim(); // sometimes user inputs white spaces without knowing it
int value;
if (s.length() == 0) {
value = 0; // obviously not a string
} else {
try{
value = Integer.valueOf(s);
} catch(NumberFormatException e) {
value = 0;
}
}
// do whatever you like here
Related Topics
Spring MVC Type Conversion:Propertyeditor or Converter
How to Show Jrbeancollectiondatasource Data with Help of Table Component
Jackson: How to Prevent Field Serialization
How to Encrypt or Decrypt with Rijndael and a Block-Size of 256 Bits
How to Set a Jlabel's Background Color
What Is Inside Com.Sun Package
Dealing with Randomly Generated and Inconsistent JSON Field/Key Names Using Gson
What Is the Right Action to Take Upon Closing Windows in Java/Swing
Why Generate Long Serialversionuid Instead of a Simple 1L
Casting a Class to an Unrelated Interface
Why Does It Compile When Casting to an Unrelated Interface
Jbutton Actionlistener - Gui Updates Only After Jbutton Is Clicked
Can Spring Security Use @Preauthorize on Spring Controllers Methods