nerdexam
Oracle

1Z0-811 · Question #9

Given the code fragment: List<String> items = new ArrayList<> (); items.add(1, "pen"); items.add(2, "pencil"); items.add(3, "erasers"); items.add("paper"); for (String x : items) {…

The correct answer is D. A runtime exception is thrown. Option D is correct because items.add(1, "pen") is called on an empty list. The index-based overload add(int index, E element) requires the index to satisfy 0 <= index <= size; since the list has size 0 at that point, index 1 is out of bounds and an IndexOutOfBoundsException is…

Arrays and Logic

Question

Given the code fragment: List<String> items = new ArrayList<> (); items.add(1, "pen"); items.add(2, "pencil"); items.add(3, "erasers"); items.add("paper"); for (String x : items) { System.out.print(x + " "); } What is the result?

Options

  • Apen pencil erasers paper
  • Bpaper pen pencil erasers
  • CA compilation error occurs.
  • DA runtime exception is thrown.

How the community answered

(34 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    9% (3)
  • D
    85% (29)

Explanation

Option D is correct because items.add(1, "pen") is called on an empty list. The index-based overload add(int index, E element) requires the index to satisfy 0 <= index <= size; since the list has size 0 at that point, index 1 is out of bounds and an IndexOutOfBoundsException is thrown immediately, before any items are printed.

Options A and B are wrong because execution never reaches the loop - the exception halts the program on the second line. Option C is wrong because the code compiles cleanly; both add(int index, E element) and add(E element) are valid overloads of List, and the integer literals are unambiguous.

Memory tip: When you see list.add(index, value) on a fresh ArrayList, ask yourself "is that index within [0, size]?" An empty list only accepts index 0 - any higher index is a runtime trap, not a compile-time one.

Topics

#ArrayList#IndexOutOfBoundsException#Method overloading#Collection API

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice