Why this code throws this exception:
public class DS3{
public static void main(String[] args) {
double r = (double)((Object)4);
System.out.println(r);
}
}
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
And this, just run fine:
public class DS4{
public static void main(String[] args) {
double r = (double)(4);
System.out.println(r);
}
}
Both are a attempt to convert integer to double, right?
4
is automatically boxed toInteger
, which cannot be casted todouble
. – Blockage4
can also be a double without casting. – Entice