MedicineMan
MedicineMan

Reputation: 15314

Double vs doubleValue in Java

if a method returns a Double, why would we call the method "doubleValue" on it? it already returns a double and in calculations, appears to evaluate correctly.

Upvotes: 8

Views: 5116

Answers (4)

Óscar López
Óscar López

Reputation: 236004

You'd call doubleValue if you need to obtain a double from a Double. The former is a primitive type, while the latter is a wrapper object type, which basically encapsulates a primitive value inside an immutable object. If possible (and I'm saying this without knowing exactly the purpose of your code), use double for all your calculations; only use Double if you need to store the values in a Collection or Map; that's because object types consume more memory and may be subject to casting operations.

It's easy to mistake double with Double (same thing applies for the other primitive types vs. wrapper types), since the compiler will automatically convert from one to the other as needed in a process known as auto-boxing (and auto-unboxing), so a little care must be taken to use the correct type.

Upvotes: 1

Wilmer
Wilmer

Reputation: 1045

doubleValue returns a primitive double from the Double Object. Depending on the scenario, you would want to get the double out of a Double.

Upvotes: 1

I82Much
I82Much

Reputation: 27326

You call 'doubleValue' on a Double object to convert from the boxed Object to the primitive data type. Since most of the time the Double is auto-unboxed to a double, you usually don't need to do this, but if you want to be explicit in your conversion, you can call this method.

Upvotes: 1

rfeak
rfeak

Reputation: 8204

Prior to Java 1.5 auto-boxing (and unboxing) didn't exist in Java. So, you would need this to extract the underlying primitive from a Double.

If you are unfamiliar with auto-boxing, you can read more here. http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

Upvotes: 9

Related Questions