This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Then use Double.valueOf(bd.doubleValue()). This will still create a new Double object though, as Double and Float objects are not cached like some instances of the other wrapper classes. This makes perfect sense; for Integer, the number of values between -128 and 127 is fixed at 256. For Double and Float there are infinite values between these bounds.
They either copied that comment from the other primitive classes, or have it there for future use. Anyway, right now it's a lie because this is the current implementation (taken from src.zip):
I definitely don't see any caching there.
Still, it's good to use valueOf, because future Java versions may add caching of some values (like 0.0, NaN, +infinity, -infinity).
Joined: Mar 17, 2005
Thanks for the reply.
Is this a good practise if i code like this (calling a method with in the constructor):
You don't even have to use the valueOf method directly. Java will automatically use it if you use autoboxing. Try:
But why do you want an object instead of the primitive?
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Joined: May 31, 2011
Stephan van Hulst wrote:You don't even have to use the valueOf method directly. Java will automatically use it if you use autoboxing.
How to determine which method is internally called during autoboxing in Java. Say if I want to make sure valueOf(double) is called and not the constructor new Double(double). Could you please share a source.
If you want to be absolutely sure the code uses valueOf(), you need to write valueOf(). Boxing makes no guarantee. In practice however, usually the valueOf() method is called. However, I can't think of a lot of situations in which you want to be absolutely sure the code uses valueOf().