ClassCastException Java Example

This Java example demonstrates the usage of ClassCastException class with an example.
  • ClassCastException has thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
  • This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.

ClassCastException Class Diagram

From the above class diagram, ClassCastException is a superclass of RunTimeException and Exception class. 

Java ClassCastException Examples

Here is a very simple example, an Integer object cannot be cast to a String object:
public class ClassCastExceptionExample {
    public static void main(String[] args) {
        Object obj = new Integer(100);
        System.out.println((String) obj);
    }
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
 at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
The next example is more complex and aims to show that an instance of the parent class cannot be cast to an instance of the child class.
package com.javaguides.corejava;

class Animal {

}

class Dog extends Animal {

}

class Lion extends Animal {

}

public class ClassCast {

    public static void main(String[] args) {

        try {
            Animal animalOne = new Dog(); // At runtime the instance is dog
            Dog bruno = (Dog) animalOne; // Downcasting

            Animal animalTwo = new Lion(); // At runtime the instance is animal
            Dog tommy = (Dog) animalTwo; // Downcasting
        } catch (ClassCastException e) {
            System.err.println("ClassCastException caught!");
            e.printStackTrace();
        }

    }

}
Output:
ClassCastException caught!
java.lang.ClassCastException: com.javaguides.corejava.Lion cannot be cast to com.javaguides.corejava.Dog
 at com.javaguides.corejava.ClassCast.main(ClassCast.java:24)

Reference


Comments