Casting an instance of an object to a primitive or object type

when I need to specify an instance of type Object in double, which of the following is better and why?

Double d = (Double) object;

or

Double d = (Double) object;

+4
source share
1 answer

The difference is that the first form will succeed if the object is null - the second will throw a NullPointerException . Therefore, if null is allowed for object , use the first - if this indicates an error condition, use the second.

It:

 double d = (double) object; 

is equivalent to:

 Double tmp = (Double) object; double t = tmp.doubleValue(); 

(Or just ((Double)object).doubleValue() , but I need to separate the two operations for clarity.)

Note that casting to double is only allowed in Java 7 - although you can’t see the Java 7 language improvement page on the page ) why this is true.

+12
source

All Articles