Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

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.

Common Causes

  • Casting an object to an incompatible type
  • Using raw types (pre-generics) and casting incorrectly
  • Incorrect assumption about the runtime type of an object
  • Deserializing objects with wrong type expectations
  • Mixing types in a collection without generics

Quick Fix (TL;DR)

Quick Solution
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

Problem
Animal animal = new Dog();
Cat cat = (Cat) animal; // ❌ Dog cannot be cast to Cat!
Solution
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

Problem
// ❌ 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!
Solution
// ✅ 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

Problem
Map data = new HashMap<>();
data.put("age", "25"); // Stored as String
Integer age = (Integer) data.get("age"); // ClassCastException!
Solution
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

Solution
// ✅ 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

  • Always use instanceof before casting - Prevents ClassCastException
  • Use generics - Type safety at compile time eliminates most casts
  • Use pattern matching (Java 16+) - Combines instanceof check and cast
  • Avoid raw types - Always parameterize collections
  • Use polymorphism instead of casting - Override methods in subclasses
  • Use Class.cast() for reflective casting - Cleaner than explicit cast
  • Enable compiler warnings - Unchecked cast warnings indicate potential issues

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


Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.