I have a string which stores a number. Now i want to parse that string and get as float.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
try {
System.out.println(Integer.parseInt(" 2 "));
} catch(NumberFormatException e) {
System.out.println("Exception caught");
}
System.out.println(Float.parseFloat(" 2.4 "));
}
}
Now in the above code if you run it it will be successfull. My QUESTION is this why does trailing spaces in case of integer throws a NumberFormatException
while parsing a float doesnt throw one ?
PS: Same is the case with booolean and double parsing.
PPS: Why is there an inconsistency in java ? And i already check the source code
As you can see in the related source code, the value will be trimmed:
So the blanks will be removed before converting to a floatValue. For more informations see the sourcecode of FloatingDecimal which is called by
Float.class
.Integer.parseInt()
do not trimm the string value:Thats why you get an Exception there