java.lang.Long cannot be cast to java.lang.Double



I have a method which takes object as an input and if the input is instanceOF Long then converting the value to double value. Below is the code :

public static void main(String[] args) {
    Long longInstance = new Long(15);
    Object value = longInstance;
    convertDouble(value);
}

static double convertDouble(Object longValue){
    double valueTwo = (double)longValue;
    System.out.println(valueTwo);
    return valueTwo;
}

but when I am executing the above code I am getting below exception :

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
at com.datatypes.LongTest.convertDouble(LongTest.java:12)
at com.datatypes.LongTest.main(LongTest.java:8)

Kindly let me know why its giving me exception.

But if directly try to cast Long object into double then there is no Exception of classCast is coming.

Long longInstance = new Long(15);
    double valueOne = (double)longInstance;
    System.out.println(valueOne);

This is confusing.

Answer

Found explaination in JLS, https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.5
Under Table 5.1. Casting conversions to primitive types

    Long l = new Long(15);
    Object o = l;

When converting Object Type to primitive then it will narrowing and then unboxing.

    double d1=(double)o; 

in above statement we are trying to narrow Object to Double, but since the actual value is Long so at runtime it throws ClassCastException, as per narrowing conversion rule defined in 5.1.6. Narrowing Reference Conversion

When converting Long Type to double, it will do unboxing and then widening.

    double d2 =(double)l; 

it will first unbox the Long value by calling longvalue() method and then do the widening from long to double, which can be without error.



Source: stackoverflow