1. Incorrect Downcasting Without Proper Type Checking
- When you cast an object to a subclass that it does not belong to, Java throws a
ClassCastException
.
Example:
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
public class ClassCastExample {
public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting (safe)
Cat myCat = (Cat) myAnimal; // Downcasting (invalid)
}
}
🛑 Output:
Exception in thread "main" java.lang.ClassCastException: Dog cannot be cast to Cat
👉 Why? myAnimal
actually refers to a Dog
, but we are trying to cast it to a Cat
, which is incorrect.
2. Casting an Object That Was Not Originally That Type
If an object is not an instance of the target class, casting it will fail.
Example:
Object obj = "Hello"; // obj holds a String
Integer num = (Integer) obj; // Trying to cast a String to Integer
🛑 Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
3. When Using instanceof
Incorrectly
If you attempt a cast without checking with instanceof
, you risk a ClassCastException
.
Example (Incorrect Way):
Animal myAnimal = new Dog();
Cat myCat = (Cat) myAnimal; // No instanceof check
👉 Fix: Always check with instanceof
before casting.
Example (Correct Way Using instanceof
):
if (myAnimal instanceof Cat) {
Cat myCat = (Cat) myAnimal;
} else {
System.out.println("Cannot cast to Cat!");
}
🟢 Output:
Cannot cast to Cat!
4. When Using Collections with Raw Types
Java allows storing different objects in raw-type collections, leading to potential ClassCastException
.
Example:
import java.util.ArrayList;
import java.util.List;
public class CollectionExample {
public static void main(String[] args) {
List rawList = new ArrayList(); // Raw type (no generics)
rawList.add("Hello"); // Adding a String
rawList.add(42); // Adding an Integer
for (Object obj : rawList) {
Integer num = (Integer) obj; // ClassCastException when trying to cast "Hello"
}
}
}
🛑 Fix: Always use generics to prevent unsafe casting.
List<Integer> intList = new ArrayList<>();
intList.add(42);
// No risk of ClassCastException here
5. When Deserializing Objects Incorrectly
If you deserialize an object and try to cast it to the wrong type, a ClassCastException
occurs.
Example:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
Dog myDog = (Dog) ois.readObject(); // If the stored object is not a Dog, this will fail
How to Prevent ClassCastException
?
- Use
instanceof
before casting
if (obj instanceof Dog) {
Dog myDog = (Dog) obj;
}
2. Use Generics to Ensure Type Safety in Collections
List<String> stringList = new ArrayList<>();
stringList.add("Hello"); // No casting issues
3. Avoid Mixing Object Types in Collections Without Proper Checks
List<Object> mixedList = new ArrayList<>();
mixedList.add("String");
mixedList.add(10);
for (Object obj : mixedList) {
if (obj instanceof Integer) {
Integer num = (Integer) obj; // Safe
}
}
4. Use Polymorphism Properly
Prefer working with abstract types (Animal instead of Dog directly).
Avoid unnecessary casting.
Conclusion
A ClassCastException
occurs when:
- You cast an object to a type it is not an instance of.
- You downcast without checking
instanceof
. - You misuse raw types in collections.
- You deserialize an object incorrectly.
✅ Best practices: Use instanceof
, generics, and proper polymorphic design to avoid this error.