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.
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());
}
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')
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