2

What do you think about the following line of code?:

 String s= "10.0";
  float f = Float.valueOf(s).floatValue();//1

Is it necessary? Why would it be better using such a syntax rather than using:

float f = Float.valueOf(s);//2

It still gives the same results taking advantage of the autoboxing function.

In short my question is: Why should one choose for the first syntax instead of the second one? Are they completely the same?

Rollerball
  • 12,618
  • 23
  • 92
  • 161

3 Answers3

5

In short my question is: Why should one choose for the first syntax instead of the second one? Are they completely the same?

Well, I would use neither of them, because both of them will generate intermediate Float object, which is almost always not needed. And wherever it will be needed, we will get it to work with boxing.

For now, you should rather just use Float.parseFloat(String) method, that generates a primitive float.


As far as similarity is concerned, no they are not completely the same. 2nd one involves auto-unboxing from Float to float, while there is no unboxing in first case. It does the conversion using the given method.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • In terms of garbage collection, it's still preferred the second one (Float.valueOf(s)) instead of (Float.valueOf(s).floatValue(). The latter one creates an anonymous object in the heap, whereas the former one does not though it uses unboxing. Which one is more efficient? I know it's better parseFloat(String) However if I had to choose between the 2, what would you suggest? (also in terms of garbage collection) thanks in advance – Rollerball Feb 11 '13 at 23:19
  • @Rollerball. No, in both the cases you are creating an object as I said in my answer. `Float.valueOf` method returns `new Float()`. Thus creating an object there only. So, no point in comparison based on garbage collections. – Rohit Jain Feb 11 '13 at 23:23
  • @Rollerball. If you force me to choose from the first two only (I will curse you for that), I'll go for the 2nd one, and make use of auto-unboxing, and won't do that task manually. – Rohit Jain Feb 11 '13 at 23:25
0

The difference is that the first one explictly converts to float,
while the second one let it outoboxed.

On Java 1.3 autoboxing is not available!

Further in some situation the autoboxing can create unwanted results.
For situations where autoboxing fails: see

Josh Bloch: Effective Java Second Edition

AlexWien
  • 28,470
  • 6
  • 53
  • 83
0

f = Float.valueOf(s);

The autoboxing feature was introduced after Java 5. This code will give an error when compiled in earlier versions of Java.

sathish_at_madison
  • 823
  • 11
  • 34