Java – White space with Integer.valueOf() causes java.lang.NumberFormatException [closed]

Tags: , ,



If you try:

Integer.valueOf(" 00");

…a java.lang.NumberFormatException is thrown. So, this is easy enough to fix by stripping any white space, even for a Java noob like me, but I’d very much appreciate any light that can be shed on why the Integer.valueOf() method was designed this way?

Wouldn’t you want it to ignore white space? After all, the white space can’t be considered ambiguous in the context of extracting an integer value from the string. If I’m missing something about this choice, I’m sure an explanation will help me grow as a coder. Thank you!

Answer

If u look at the java docs , Integer.valueOf(String) calls

return Integer.valueOf(parseInt(s, 10));

and according to Java docs again for parseInt

The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign ‘-‘(‘u005Cu002D’) to indicate a negative value or anASCII plus sign ‘+’ (‘u005Cu002B’) to indicate a positive value.

Space violate the above rule hence number format exception.



Source: stackoverflow