
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is a ClassCastException and When It Will Be Thrown in Java
In this article, we will be learning about ClassCastException in Java. But before we jump into this, we'll understand what an exception is in Java. After that, we'll learn why and when ClassCastException occurs, look at real-world code examples that throw this exception, and finally learn how to avoid or resolve it.
What is an Exception in Java?
An exception in Java is an event that disrupts the normal flow of the program. Java provides a way to handle these errors gracefully using try-catch blocks. There are 2 types of exceptions:
-
Checked Exceptions - Checked at compile time. Example: IOException, SQLException
- Unchecked Exceptions - Checked at runtime. Example: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException
What is ClassCastException?
The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type.
When will ClassCastException be thrown?
Case 1: When we try to cast an object of the Parent class to its Child class type, this exception will be thrown.
Example
class Animal {} class Dog extends Animal {} public class Test1 { public static void main(String[] args) { Animal animal = new Animal(); Dog dog = (Dog) animal; // Causes ClassCastException } }
Output
Exception in thread "main" java.lang.ClassCastException: Animal cannot be cast to Dog
Case 2: When we try to cast an object of one class into another class type that has not extended the other class, or they don't have any relationship between them.
Example
class Cat {} class Bird {} public class Test2 { public static void main(String[] args) { Cat cat = new Cat(); Bird bird = (Bird) cat; // Causes ClassCastException } }
Output
Exception in thread "main" java.lang.ClassCastException: Cat cannot be cast to Bird
Casting in Inheritance Hierarchy
Below is an example to show the casting in the inheritance hierarchy:
class ParentTest { String parentName; ParentTest(String n1){ parentName = n1; } public void display() { System.out.println(parentName); } } class ChildTest extends ParentTest { String childName; ChildTest(String n2) { super(n2); childName = n2; } public void display() { System.out.println(childName); } } public class Test { public static void main(String args[]) { ChildTest ct1 = new ChildTest("Jai"); ParentTest pt1 = new ParentTest("Adithya"); pt1 = ct1; pt1.display(); ParentTest pt2 = new ParentTest("Sai"); ChildTest ct2 = (ChildTest)pt2; } }
Output
Jai Exception in thread "main" java.lang.ClassCastException: ParentTest cannot be cast to ChildTest at Test.main(Test.java:30)
How to Resolve ClassCastException
Below are some ways to resolve the ClassCastException :
1. Use instanceof Check Before Casting
Use instanceof to check the actual type of the object before casting.
if (pt2 instanceof ChildTest) { ChildTest ct2 = (ChildTest) pt2; } else { System.out.println("Cannot cast to ChildTest."); }
2. Use Polymorphism to Avoid Casting
Design your program using polymorphism so that downcasting is not needed.
ParentTest pt = new ChildTest("Jai"); pt.display();
3. Use Generics to Catch Type Issues at Compile Time
You should use generics that can help you to prevent casting issues, especially in collections.
List list = new ArrayList<>(); String str = list.get(0); // No need to cast
4. Avoid Unrelated Casts
Never try to cast between unrelated classes. This will always result in a ClassCastException.