ClassCastException in Java — How to Fix (2026) | Tutorials Logic
What is This Error?
The ClassCastException is thrown when you try to cast an object to a class it is not an instance of. Java allows you to cast objects in the type hierarchy, but if the actual runtime type doesn't match the target type, this exception is thrown.
Error Message:
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integerjava.lang.ClassCastException: Dog cannot be cast to Cat
Common Causes
Quick Fix (TL;DR)
Object obj = "Hello";
// ❌ Problem
Integer num = (Integer) obj; // ClassCastException!
// ✅ Solution 1: Check with instanceof first
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}
// ✅ Solution 2: Pattern matching (Java 16+)
if (obj instanceof Integer num) {
System.out.println(num + 1); // num is already cast
}
Common Scenarios & Solutions
Scenario 1: Incorrect Downcast
Animal animal = new Dog();
Cat cat = (Cat) animal; // ❌ Dog cannot be cast to Cat!
Animal animal = new Dog();
// ✅ Check before casting
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.bark();
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
cat.meow();
}
// ✅ Java 16+ pattern matching
if (animal instanceof Dog dog) {
dog.bark(); // dog is already typed as Dog
}
Scenario 2: Raw Collections
// ❌ Raw type — no type safety
List list = new ArrayList();
list.add("Hello");
list.add(42);
Integer num = (Integer) list.get(0); // ClassCastException! It's a String!
// ✅ Use generics for type safety
List strings = new ArrayList<>();
strings.add("Hello");
// strings.add(42); // Compile error — caught early!
String s = strings.get(0); // No cast needed!
Scenario 3: Object from Map
Map data = new HashMap<>();
data.put("age", "25"); // Stored as String
Integer age = (Integer) data.get("age"); // ClassCastException!
Map data = new HashMap<>();
data.put("age", "25");
// ✅ Check type before casting
Object ageObj = data.get("age");
if (ageObj instanceof Integer) {
Integer age = (Integer) ageObj;
} else if (ageObj instanceof String) {
Integer age = Integer.parseInt((String) ageObj);
}
// ✅ Or use a typed helper
@SuppressWarnings("unchecked")
public static T getAs(Map map, String key, Class type) {
Object value = map.get(key);
if (type.isInstance(value)) return type.cast(value);
throw new ClassCastException("Expected " + type + " but got " + value.getClass());
}
Scenario 4: Polymorphism with instanceof
// ✅ Safe polymorphic dispatch
List shapes = Arrays.asList(new Circle(5), new Rectangle(3, 4));
for (Shape shape : shapes) {
if (shape instanceof Circle c) {
System.out.println("Circle area: " + Math.PI * c.getRadius() * c.getRadius());
} else if (shape instanceof Rectangle r) {
System.out.println("Rectangle area: " + r.getWidth() * r.getHeight());
}
}
Best Practices to Avoid This Error
Related Errors
Key Takeaways
- ClassCastException occurs when casting an object to an incompatible type
- Always use instanceof to check the type before casting
- Java 16+ pattern matching combines instanceof check and cast in one step
- Use generics to get compile-time type safety and eliminate most casts
- Avoid raw types — always parameterize collections with type parameters
- Prefer polymorphism over type checking and casting when possible
Frequently Asked Questions
Level Up Your Core java Skills
Master Core java with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related Java Topics