ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
List<Integer> l = new ArrayList<>(List.of(1, 2, 3));
Iterator<Integer> it = l.iterator();
it.next();
it.remove();
System.out.print(l + " ");
it.remove();
  1. A. [2, 3] [3]
  2. B. "[2, 3] " is printed, then ConcurrentModificationException is thrown
  3. C. [1, 2, 3] then IllegalStateException
  4. D. "[2, 3] " is printed, then IllegalStateException is thrown

Correct answer: D. "[2, 3] " is printed, then IllegalStateException is thrown

Iterator.remove may be called only once per call to next(); the second remove without an intervening next throws IllegalStateException.

More OOP with C++ and Java questions

Exams that ask this topic