Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 472
Bhupendra Nath Avatar asked Sep 24 '15 09:09

Bhupendra Nath


People also ask

How do I resolve Java Lang ClassCastException error?

// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.


1 Answers

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.

like image 80
Sanket Bajoria Avatar answered Sep 23 '22 02:09

Sanket Bajoria