ClassCastException in Java

      No Comments on ClassCastException in Java

ClassCastException occurs when parent class is tried to typecast to child class.

e.g. Object obj = new Object();
Integer i = (Integer)obj; //will throw ClassCastException

ClassCastException is a subclass of RuntimeException.
It is unchecked exception.
It is thrown by JVM at runtime.

Examples of ClassCastException

Let’s take some examples to understand this exception:

(1) Object obj = new Object();
Integer i = (Integer)obj; // will throw ClassCastException

This would throw exception as superclass Object is typecast to subclass Integer.

(2) Integer i = new Integer(100);
Object obj = i; // Valid
Object obj1 = (Object)i; // Valid

These are valid as subclass Integer is typecast to superclass Object.

(3) Object o = new Integer(230);
Integer i = (Integer)o; //Valid as the actual object is Integer only.

This is also valid as actual object is of type Integer only.

Demo Program : ClassCastException

package com.masterjavatutorial;
public class TestExample {
    public static void main(String[] args) {
         Object o = new Integer(100);
         Integer y =(Integer)o;
	 Object obj = new Object();
	 Integer i = (Integer)obj;

Output of the above program is as below:

Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer
	at com.masterjavatutorial.TestExample.main(

In the above program , ClassCastException is thrown when obj of type Object is typecast to Integer. Object is superclass of all classes in Java. Integer is subclass of Object class.