ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
List<Integer> l = new ArrayList<>(List.of(2, 2, 3, 2, 4));
for (int i = 0; i < l.size(); i++)
    if (l.get(i) == 2) l.remove(i);
System.out.print(l);
  1. A. [3, 4]
  2. B. [2, 3, 4]
  3. C. [2, 3, 2, 4]
  4. D. A ConcurrentModificationException is thrown

Correct answer: B. [2, 3, 4]

Removing at index i shifts the next element into index i, but the loop then moves on to i + 1 and skips it: the second 2 survives. An index loop does not throw ConcurrentModificationException.

More OOP with C++ and Java questions

Exams that ask this topic