nerdexam
Oracle

1Z0-811 · Question #17

Given the code fragment: List<String> names = new ArrayList<>(); names.add("Julia"); names.add("Peter"); for (Iterator<String> itr = names.iterator(); itr.hasNext();) {…

The correct answer is C. Julia Peter. Option C is correct because ArrayList preserves insertion order, so the iterator visits "Julia" (added first) then "Peter" (added second), printing them on separate lines exactly as inserted. Option A is wrong because the code is syntactically valid Java - Iterator<String> with…

Arrays and Logic

Question

Given the code fragment: List<String> names = new ArrayList<>(); names.add("Julia"); names.add("Peter"); for (Iterator<String> itr = names.iterator(); itr.hasNext();) { System.out.println(itr.next()); } What is the result?

Options

  • AA compilation error occurs.
  • BA runtime exception is thrown.
  • CJulia Peter
  • DPeter Julia

How the community answered

(40 responses)
  • A
    8% (3)
  • B
    3% (1)
  • C
    88% (35)
  • D
    3% (1)

Explanation

Option C is correct because ArrayList preserves insertion order, so the iterator visits "Julia" (added first) then "Peter" (added second), printing them on separate lines exactly as inserted. Option A is wrong because the code is syntactically valid Java - Iterator<String> with hasNext() and next() is the standard, compiler-approved pattern. Option B is wrong because no exception is triggered: the list is not modified during iteration (which would cause a ConcurrentModificationException), and next() is never called past the end of the list. Option D is wrong because it implies reverse order, which would only occur with a stack-like structure (e.g., Deque) or explicit reversal - ArrayList's iterator always goes index 0 → N.

Memory tip: Think of ArrayList as a numbered line - whoever joins first gets spot #0, and the iterator always starts from the front of the line.

Topics

#Iterator#ArrayList#Collections API#Iteration Order

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice