ClassCastException in Java — What It Means and How to Fix It

What Java's ClassCastException means and how to fix it.

Published November 2, 2026

ClassCastException is thrown when you cast an object to a type it is not an instance of.

What it means and why it happens

Typical causes: raw types and unchecked generics, wrong assumptions about collection contents or bad downcasts.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer

Practical examples

Code that triggers it

Object o = "text";
Integer i = (Integer) o;

The fix

Object o = "text";
if (o instanceof Integer i) { use(i); }

Use generics

List<String> names = new ArrayList<>();   // no cast needed

Common mistakes

  • Raw types such as List instead of List<String>.
  • Blind downcasting.
  • Heap pollution through unchecked warnings.

Key takeaways

  • ClassCastException: ClassCastException is thrown when you cast an object to a type it is not an instance of.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

How can I avoid casts?

Use generics and pattern matching for instanceof.

How do I find which line caused ClassCastException?

The error message and stack trace show the file and line; start there and work backwards.

More Java articles