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

You try to convert Object to double, since your parameter of convertDouble is of Type object. Thus the auto-unboxing will not work. There would be two solutions: first, cast the Object to Long (checking with instanceof) second, use Long as Parameter

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

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

If you want to convert different types of arguments withing the convertDouble method, you may check with instanceof and then convert the Object to the type, you eventually have


First check if the Object is instanceof Long and then call valueOf of Long obejct

Snippet:

static double convertDouble(Object longValue){
        double valueTwo = -1; // whatever to state invalid!

        if(longValue instanceof Long) 
           valueTwo = ((Long) longValue).doubleValue();

        System.out.println(valueTwo);
          return valueTwo;
     }

If you are not sure what number type the object would be then I would recommend using this code snippet:

double d = 0.0;
if (obj instanceof Number) {
    d = ((Number) obj).doubleValue();
}

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.

Tags:

Java