-1
public class Test8 {
   public static void main (String args[]) {
      Number numberRef = new Integer(0);
      Double doubleRef = (Double)numberRef;
   }
}

It shows me exception at runtime:

Exception in thread "main" java.lang.ClassCastException:
  java.lang.Integer cannot be cast to java.lang.Double

Why is it so?

arshajii
  • 127,459
  • 24
  • 238
  • 287
user2423706
  • 159
  • 4
  • 15
  • 3
    Because `Integer` is not a sub-class of `Double`? – Oliver Charlesworth Jul 22 '13 at 03:10
  • 1
    Yeah, can't cast `Integer` into `Double`. arshajii below has the right answer, use `doubleValue()`. – Mark M Jul 22 '13 at 03:14
  • Also worth mentioning that Integer and int, Double and double are different things. – sashkello Jul 22 '13 at 03:16
  • 1
    Some beginners tend to think that casting is some kind of conversion, but it's not. Casting is just telling the compiler "No, you think there's a chance this object may not be an instance of this class but I can assure you it will be, so try to compile it anyway". Needless to say, when at runtime the object is not an instance of the class you said it would be, a runtime exception is thrown. – Doodad Jul 22 '13 at 03:29

3 Answers3

4

You are trying to cast an instance of Integer to a reference Double which cannot happen. Integer and Double are two different classes and objects of each cannot be simply cast to each other

Number is a common super class for Integer and Double, hence an instance of Double or Integer can be upcasted to Number. In other words, Integer IS A Number, Double IS A Number BUT, Integer IS NOT A Double

Integer i = new Integer(0);
Double d = new Double(1);
Number ni = i;
Number di = d;
Integer id = d; //invalid;
Double dd = i; //invalid
Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
2

You are receiving a ClassCastException in accordance with JLS §5.5.3:

Here is the algorithm to check whether the run-time type R of an object is assignment compatible with the type T which is the erasure (§4.6) of the type named in the cast operator. If a run-time exception is thrown, it is a ClassCastException.

If R is an ordinary class (not an array class):

  • If T is a class type, then R must be either the same class (§4.3.4) as T or a subclass of T, or a run-time exception is thrown.

  • ...

...

Note that Integer is not a subclass of Double.


What about

Double doubleRef = numberRef.doubleValue();

instead?

doubleValue() is a method of the Number class.

Community
  • 1
  • 1
arshajii
  • 127,459
  • 24
  • 238
  • 287
0

numberRef.doubleValue(); will return the double value of the Integer which could then be assigned to the Double

Documentation -

http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html