If a ClassCastException
is one of the most common exceptions in Java. It is a runtime exception that occurs when the application code attempts to cast an object to another class of which the original object is not an instance. For example, a String object cannot be cast to an Integer object and attempting to do so will result in a ClassCastException
.
Since the ClassCastException
is an unchecked exception, it doesn't need to be declared in the throws clause of a method or constructor.
Sources of ClassCastException
Some of the most common sources of ClassCastException
in Java are:
- Using collections like HashMap, ArrayList and HashTable which do not use Java Generics.
- Using methods which were written on interfaces prior to Java 5 that use polymorphism.
- Not using type-safety when casting objects in Java.
ClassCastException Example
Here is an example of a ClassCastException
thrown when a String is attempted to be cast to an Integer:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new String("Hello");
System.out.println((Integer) obj);
}
}
In this example, the String obj
is attempted to be cast to an Integer. Since it is not an instance of the Integer class, this operation throws a ClassCastException
:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
How to Fix ClassCastException
To fix the ClassCastException
in the above example, the object type should be checked before performing the cast operation:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new String("Hello");
 
if (obj instanceof Integer) {
System.out.println((Integer) obj);
} else {
System.out.println(obj);
}
}
}
The code is updated with a check that makes sure obj
is an instance of the Integer class before it is cast to an Integer. The cast operation is only done if the check passes. The above code runs successfully without throwing a ClassCastException
Hello
How to Avoid ClassCastException
The ClassCastException
can be avoided using checks and preventive techniques like the following:
- When trying to cast an object to another class, make sure that the new type belongs to one of its parent classes. The instanceof operator in Java can be used to ensure this.
- Using Generics, since they provide compile time checks and can be used to ensure type-safety.
Track, Analyze and Manage Java Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.