Java casting confusion

Can someone tell me why the following casting leads to a compile-time error:

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

But why not the following:

 Long l = (Long)Math.pow(5,2); 
+4
source share
3 answers

Math.pow(5,2) is a double that can be attributed to long . It can not be attributed to long .

This, however, works great 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

+10
source

You cannot use a primitive type (for example, double ) directly for an object. This is just not how Java works. There are some situations where a language can apply a suitable object creation to you, for example, arguments to a function call.

+4
source

Since primitive types are not objects with all effects, also if java added some workarounds (for example, implicit unpacking of these types).

You can choose it in different ways, for example:

 Long l3 = ((Double)Math.pow(5, 2)).longValue(); 

This works because Java can:

  • for implicit transfer from a primitive type to another when you refer to them only with a regular type declaration, for example: int to long
  • for implicit casting from a box type to another, for example. int to long
  • to switch between boxed and unboxed types when they are the same type, e.g. long to long
+1
source

Source: https://habr.com/ru/post/1303968/


All Articles