Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between initializing a Float with a String, or doing parseFloat?

Tags:

java

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?

like image 912
beechboy2000 Avatar asked Mar 21 '23 02:03

beechboy2000


1 Answers

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.

like image 85
Sotirios Delimanolis Avatar answered Apr 06 '23 04:04

Sotirios Delimanolis