Illegal cast between incompatible reference types at runtime.
A ClassCastException is thrown when you try to cast an object to a class or interface that it is not an instance of. Java allows casting in the type hierarchy, but if the actual runtime type of the object is incompatible with the target type, the cast fails.
This usually happens when: using raw/unchecked collections (pre-generics code), downcasting without checking with `instanceof`, deserializing data into the wrong type, or working with heterogeneous collections where the assumed type doesn't match.
1import java.util.ArrayList;2import java.util.List;3 4public class Main {5 public static void main(String[] args) {6 List<Object> items = new ArrayList<>();7 items.add("Hello");8 items.add(42);9 items.add(3.14);10 11 // Incorrectly assuming all items are Strings12 for (Object item : items) {13 String s = (String) item; // Fails on Integer and Double14 System.out.println(s.toUpperCase());15 }16 }17}1import java.util.ArrayList;2import java.util.List;3 4public class Main {5 public static void main(String[] args) {6 List<Object> items = new ArrayList<>();7 items.add("Hello");8 items.add(42);9 items.add(3.14);10 11 // Fix 1: Check with instanceof before casting12 for (Object item : items) {13 if (item instanceof String s) { // Java 16+ pattern matching14 System.out.println(s.toUpperCase());15 } else {16 System.out.println("Not a string: " + item);17 }18 }19 20 // Fix 2: Use a properly typed collection if elements are all the same type21 List<String> strings = List.of("hello", "world");22 for (String s : strings) {23 System.out.println(s.toUpperCase());24 }25 }26}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The list contains a `String`, an `Integer`, and a `Double`. When the loop reaches the `Integer` value `42`, the cast `(String) 42` fails because `Integer` is not a subtype of `String`. Java throws `ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String`.