Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an instance of Object to primitive type or Object Type

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;

like image 460
Gautam Avatar asked Apr 01 '13 11:04

Gautam


1 Answers

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.

like image 139
Jon Skeet Avatar answered Sep 19 '22 01:09

Jon Skeet