ClassCastException
is an unchecked exception i.e. it is not identified at compile time. The ClassCastException
is since JDK 1.0 class ClassCastExceptionDemo
{
public static void main(String args[])
{
Object ob=new Integer(10);
// ClassCastException occurs
System.out.println("The value is "+(String)ob);
}
}
Output
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer canno
t be cast to java.lang.String
at ClassCastExceptionDemo.main(ClassCastExceptionDemo.java:9)
Explaining the reason
The first statement is OK. It is well written in fact. It produces no error. We know that java.lang.Object is a super class for every class in Java,of course for java.lang.Integer too. We also know that, a super class reference variable can hold a sub class' object. But when you do so, remember that you'll not be able to call the sub class' object's own methods (the methods that were not inherited from the super class and belong to the sub class only) say intValue() for example. The method intValue() is written only in java.lang.Integer and it is not in java.lang.Object. From the above statement, you cannot call ob.intValue(), this produces a compile time error.
See the next statement, the Object class' reference ob is holding the object of it's sub class java.lang.Integer which is not a super class of the String class. When you do such a type cast between classes, it means that you are type casting objects not references. Though the reference is of the type java.lang.Object which is a super class of java.lang.String, the object ob is holding the java.lang.Integer object and you cannot type cast java.lang.Integer into java.lang.String.
This is what the ClassCastException is about. As you can observe from the output of the example, it is mentioned that cannot typecast java.lang.Integer into java.lang.String. Understood? Simple is that.