ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4, 5));
l.subList(1, 3).clear();
System.out.print(l);
  1. A. [1, 4, 5]
  2. B. [1, 2, 3, 4, 5]
  3. C. [4, 5]
  4. D. [1, 5]

Correct answer: A. [1, 4, 5]

subList is a view of the backing list, so clearing indices 1 and 2 (elements 2 and 3) removes them from l itself. This is a standard idiom for removing a range.

More OOP with C++ and Java questions

Exams that ask this topic