Search code examples
javaunboxing

Why unboxing doesn't work : Unresolved compilation error: Cannot cast from double to Long?


As per my understanding, Java automatically takes care of Autoboxing and Unboxing i.e., conversion of Primitives to Object Wrappers and vice a versa. However, unboxing doesn't seem to be working in below code.

public class TestMath {
    public static void main(String[] args) {
        Long resultLong = (Long) Math.pow(10, 10);
        System.out.println(resultLong);
    }
}

The above code gives me compilation error until I manually do unboxing by replacing (Long) with (long). I would like to understand the reason behind this.

The compilation error is as shown below:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from double to Long


Solution

  • Math.pow(10, 10) returns a double, which can be auto-boxed into a Double, not into a Long.

    If you explicitly cast the result to long, the compiler can auto-box the long to Long.

    As to why (Long) Math.pow(10, 10) doesn't work - there is no conversion from double to Long defined in the JLS. The only supported boxing conversions are from a primitive to its corresponding reference type:

    5.1.7. Boxing Conversion

    Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

    • From type boolean to type Boolean

    • From type byte to type Byte

    • From type short to type Short

    • From type char to type Character

    • From type int to type Integer

    • From type long to type Long

    • From type float to type Float

    • From type double to type Double

    • From the null type to the null type