ClassCastException in java
In this article, we will understand what is ClassCastException
in java, what is its cause, how to avoid it and handle it with examples.
ClassCastException
belongs to java.lang
package and is thrown when objects are casted to some other types.It is an unchecked exception and so it extends
java.lang.RuntimeException
class in java.Cause
ClassCastException
is thrown in any of the below cases
- Trying to cast a parent or super class object to child class. This is also called downcasting.
Below is a program example of this caseclass Parent { } class Child extends Parent { } // below two lines will raise exception Parent o = new Parent(); Parent o1 = (Child)o;
Result is
Exception in thread “main” java.lang.ClassCastException: class Parent cannot be cast to class Child
- Trying to cast an object of one type to another when they are no way related to each other.
Example of such a scenario isList l = new ArrayList<>(); l.add(5); l.add("A"); // cast integer to string String s = (String)l.get(0);
Output will be
Exception in thread “main” java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
Since we are trying to cast an element of type
Integer
toString
, when they do not have any relation.
Java docs for ClassCastException
state,
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
Though the official docs state downcasting as the reason, but it is also raised due to casting between incompatible types.
There are two ways to handle
ClassCastException
.
- Using instanceof operator
Whenever you need to perform type casting, useinstanceof
operator withif
statement.
It returnstrue
if types are compatible and it is safe to cast, otherwise returnsfalse
. Example,Parent o = new Parent(); if(o instanceof Child) { Parent o1 = (Child)o; }
- Java exception handling
Surround program statements which are performing type casting with java try-catch block. Example,List l1 = new ArrayList<>(); l1.add(1); l1.add("A"); try { String s = (String)l1.get(0); } catch (ClassCastException e) { System.out.println("Incompatible casting"); }
Hope the article was useful in clarifying the reason of ClassCastException
in java and how to handle it to make an application safe from this error.