Casting an instance of Object to primitive type or Object Type
Asked Answered
M

1

6

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

Double d = (Double) object;

Or

double d = (double) object;

Mascarenas answered 1/4, 2013 at 11:26 Comment(1)
If you try to compile these two options you'll notice something about the second...Hatten
C
17

The difference is that the first form will succeed if object is null - the second will throw a NullPointerException. So if it's valid for object to be null, use the first - if that indicates an error condition, use the second.

This:

double d = (double) object;

is equivalent to:

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

(Or just ((Double)object).doubleValue() but I like separating the two operations for clarity.)

Note that the cast to double is only valid under Java 7 - although it's not clear from the Java 7 language enhancements page why that's true.

Carnallite answered 1/4, 2013 at 11:29 Comment(6)
You can do double d = (double) (Double) object; in versions of java pre 1.7, this will throw the NPE from the (double) cast if object is null.Telephonist
@bmorris591: Indeed - or just call doubleValue() directly.Carnallite
@bmorris591: I am getting NPE in both jdk 1.6 and 1.7 !Mascarenas
@mataug: Then presumably object is null.Carnallite
From @bmorris591 comment I assumed that NPE will be thrown only in pre 1.7, and in 1.7 I would probably get 0 .Mascarenas
@mataug: No, prior to Java 7 it wouldn't compile.Carnallite

© 2022 - 2024 — McMap. All rights reserved.