Could anyone please tell me why the following casting is resulting in compile time error:
Long l = (Long)Math.pow(5,2);
But why not the following:
long l = (long)Math.pow(5,2);
Could anyone please tell me why the following casting is resulting in compile time error:
Long l = (Long)Math.pow(5,2);
But why not the following:
long l = (long)Math.pow(5,2);
You can't cast a primitive type (like double
) directly to an object. That's just not how Java works. There are some situations where the language can apply the appropriate object creation for you, like function call arguments.
Math.pow(5,2)
is a double
, which can be cast to long
. It can not be cast to Long
.
This would however work fine, thanks to autoboxing which converts between long
and Long
:
Long l = (long)Math.pow(5,2);
To summarize, you can convert double --> long
and long --> Long
, but not double --> Long
Because primitive types are not object at all effects also if java added some workarounds (like implicit unboxing of these types).
You can sole it in various ways, like:
Long l3 = ((Double)Math.pow(5, 2)).longValue();
This works because Java is able:
int
to long
Int
to Long
long
to Long