开发者

java casting confusion

开发者 https://www.devze.com 2022-12-22 23:21 出处:网络
Could anyone please tell me why the following casting is resultin开发者_如何学Pythong in compile time error:

Could anyone please tell me why the following casting is resultin开发者_如何学Pythong in compile time error:

Long l = (Long)Math.pow(5,2);

But why not the following:

long l = (long)Math.pow(5,2);


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


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消