Does anybody know why the following snippet does not throw a NumberFormatException
?
public class FlIndeed {
public static void main(String[] args) {
System.out.println(new FlIndeed().parseFloat("0xabcP2f"));
}
public float parseFloat(String s) {
float f = 0.0f;
try {
f = Float.valueOf(s).floatValue();
return f;
}
catch (NumberFormatException nfe) {
System.out.println("Invalid input " + s);
}
finally {
System.out.println("It's time to get some rest");
return f;
}
}
}
Note that there is a P inside .parseFloat("0xabcP2f"));
Because it do accept hexadecimal values and you are passing a valid hexadecimal value.
From Doc (s = input String argument)
s should constitute a FloatValue as described by the lexical syntax rules:
FloatValue: Signopt NaN Signopt Infinity Signopt FloatingPointLiteral Signopt HexFloatingPointLiteral SignedInteger HexFloatingPointLiteral: HexSignificand BinaryExponent FloatTypeSuffixopt HexSignificand: HexNumeral HexNumeral . 0x HexDigitsopt . HexDigits 0X HexDigitsopt . HexDigits BinaryExponent: BinaryExponentIndicator SignedInteger BinaryExponentIndicator: p P
about NumberFormatException
thrown from valueOf
where Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger and FloatTypeSuffix are as defined in the lexical structure sections of the of the Java Language Specification. If s does not have the form of a FloatValue, then a NumberFormatException is thrown.
About use of p in hex: P in constant declaration