While coding a quick application, I noticed that there are two ways you could convert a String into a Float or an Integer.
Float f = new Float("0.0327f");
Float f = Float.parseFloat("0.0327f");
Similar methods exist for Integers. How are these two different?
Check their implementation (Oracle JDK 7)
public Float(String s) throws NumberFormatException {
// REMIND: this is inefficient
this(valueOf(s).floatValue());
}
where valueOf(String) is
public static Float valueOf(String s) throws NumberFormatException {
return new Float(FloatingDecimal.readJavaFormatString(s).floatValue());
}
while parseFloat(String) is
public static float parseFloat(String s) throws NumberFormatException {
return FloatingDecimal.readJavaFormatString(s).floatValue();
}
In the end, the two ways to generated the Float are equivalent. I say equivalent because in your example,
Float f = Float.parseFloat("0.0327f");
the float result of parseFloat will be boxed to a Float. The boxing process will basically wrap the previous call, ie. Float.valueOf(Float.parseFloat("0.0327f")) and the resulting Float's reference will be assigned to f.
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