Reputation: 13108
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?
Upvotes: 2
Views: 540
Reputation: 833
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.
Upvotes: 0
Reputation: 213261
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.
Upvotes: 5
Reputation: 28737
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
Upvotes: 0