Exceptions: ClassCastException fires when a bad cast is used, not when it is made

Generic type checks are erased at runtime, so an unchecked cast to a wildcard-typed generic list compiles and succeeds silently; the real ClassCastException only surfaces later, when code reads an element back out as the wrong type.

Code
List<Object> objects = new ArrayList<>();
objects.add("not a number");
List<?> wildcardView = objects;
@SuppressWarnings("unchecked")
List<Integer> unsafe = (List<Integer>) wildcardView;
System.out.println("Unchecked cast succeeded, list is still: " + unsafe);
try {
    int first = unsafe.get(0);
    System.out.println("Unreachable: " + first);
} catch (ClassCastException e) {
    System.out.println("Failed on use: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
Output
Unchecked cast succeeded, list is still: [not a number]
Failed on use: ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms