Tutorial :java casting confusion



Question:

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);  


Solution:1

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


Solution: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.


Solution:3

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:

  • to implicit cast from a primitive type to another one when you refer to them just with normal type declaration eg: int to long
  • to implicit cast from a boxed type to another one eg. Int to Long
  • to switch between boxed and unboxed type when they are the same type eg long to Long

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »