ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
List<Integer> l = new ArrayList<>(10);
System.out.print(l.size() + " ");
l.set(0, 1);
System.out.print(l);
  1. A. 0 [1]
  2. B. 10 [1, null, null, …]
  3. C. "10 " is printed, then IndexOutOfBoundsException is thrown
  4. D. "0 " is printed, then IndexOutOfBoundsException is thrown

Correct answer: D. "0 " is printed, then IndexOutOfBoundsException is thrown

The constructor argument is the initial CAPACITY, not the size; the list is empty, and set(0, …) requires an existing element at index 0.

More OOP with C++ and Java questions

Exams that ask this topic