ClassCastException
JavaFATALCommonType
Invalid class cast
Quick Answer
Use instanceof before casting, or use generics to enforce types at compile time.
What this means
Thrown when code tries to cast an object to a type it is not an instance of at runtime.
Why it happens
- 1Casting from a collection that lost generic type info (erasure)
- 2Incorrect assumption about object type from external API
Fix
instanceof pattern matching (Java 16+)
instanceof pattern matching (Java 16+)
if (obj instanceof String s) {
System.out.println(s.length()); // s is String
}Why this works
Pattern matching casts and binds in one step, eliminating the explicit cast.
Code examples
Triggerjava
Object x = Integer.valueOf(42); String s = (String) x; // ClassCastException
Pattern matching instanceofjava
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}Use genericsjava
List<String> names = new ArrayList<>();
names.add("Alice");
String n = names.get(0); // no cast neededSame error in other languages
Sources
Official documentation ↗
Java SE Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev