When I run parseInt:
Integer.parseInt(myString);
it throws:
NumberFormatException: For input string: ""
Does this mean I have do something like this?
if(StringUtils.isNotBlank(myString))
return Integer.parseInt(myString);
else
return 0;
To avoid this error, you should trim() the input string before passing it to parse methods like the parseInt() or parseFloat().
The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps: Surround the statements that can throw an NumberFormatException in try-catch blocks. Catch the NumberFormatException. Depending on the requirements of the application, take necessary action.
NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric. Many Java methods which convert String to numeric type like Integer. parseInt() which convert String to int, Double.
The NumberFormatException is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is not appropriate or illegal.
The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
Yes, but: Wrap it in a thin method (and eliminate the redundant else
), or use an existing implementation, like Commons Lang's NumberUtils.toInt(str, defaultValue)
:
NumberUtils.toInt(myString, 0);
This method handles null
values and conversion failures.
Writing the same thing on your own is straight-forward:
NumberFormatExtension
exceptionWell, you could use the conditional operator instead:
return StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
If you need to do this in multiple places, you'd probably want to put this into a separate method. Note that you should also consider situations where myString
is null, or contains non-numeric text.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With