ProgrammingVery hardProduct company interview · GATE level

What happens when this code runs?

What happens when this code runs?
List<String> strs = new ArrayList<>();
strs.add("a");
List raw = strs;
raw.add(42);
System.out.print(strs.size() + " ");
String s = strs.get(1);
System.out.print(s);
  1. A. It does not compile, because raw.add(42) adds an Integer to a List<String>
  2. B. It prints 2 and then throws ClassCastException at the line String s = strs.get(1);
  3. C. It throws ClassCastException at raw.add(42)
  4. D. It prints 2 42

Correct answer: B. It prints 2 and then throws ClassCastException at the line String s = strs.get(1);

Generics are erased: at run time both variables refer to the same ArrayList of Objects. Adding through the raw type only produces an unchecked warning and succeeds, so the list holds "a" and 42 and its size is 2. The compiler inserts a cast to String where the element is used as a String, so strs.get(1) fails there with ClassCastException - far from the line that caused the problem, which is what heap pollution means.

More OOP with C++ and Java questions

Exams that ask this topic