ProgrammingModerateHCL · Tech Mahindra pattern

What is printed?

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

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

add(index, element) inserts 5 at index 1 and shifts the later elements right, so [1, 2] becomes [1, 5, 2]. It neither replaces (that is set) nor appends.

More OOP with C++ and Java questions

Exams that ask this topic