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);- A. It does not compile, because raw.add(42) adds an Integer to a List<String>
- B. It prints 2 and then throws ClassCastException at the line String s = strs.get(1);
- C. It throws ClassCastException at raw.add(42)
- 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
- What is printed? java final String a = "Ja"; String b = "Ja"; String x = a + "va"; String y = b + "va"; String z = y.intern()…
- What is printed? java class K { int id; K(int id) { this.id = id; } public boolean equals(Object o) { return o instanceof K && ((K) o).id…
- What happens when this code runs? java Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0)…
- Which lines fail to compile? java short s = 1; s = s + 1; // L1 s += 1; // L2 char c = 'A'; c++; // L3 final int k = 10; byte b1 = k; //…
- Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.) java // A try…
- What is printed? java class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } // in main…