nerdexam
Oracle

1Z0-819 · Question #133

Given: 1. Iterator iter = List.of(1,2,3).iterator(); 2. while (iter.hasNext()) { 3. foo(iter.next()); 4. } 5. Iterator iter2 = List.of(1,2,3).iterator(); 6. while (iter.hasNext()) { 7…

The correct answer is A. The loop starting line 11. Option A is correct because the for loop on line 10 declares Iterator iter in its initializer - but iter was already declared on line 1 in the same enclosing scope. Java does not allow a local variable to be re-declared in the same scope (or a nested scope within the same…

Controlling Program Flow

Question

Given: 1. Iterator iter = List.of(1,2,3).iterator(); 2. while (iter.hasNext()) { 3. foo(iter.next()); 4. } 5. Iterator iter2 = List.of(1,2,3).iterator(); 6. while (iter.hasNext()) { 7. bar(iter2.next()); 8. } 9. } 10. for (Iterator iter = List.of(1,2,3).iterator(); iter.hasNext(); ) { 11. foo(iter.next()); 12. } 13. for (Iterator iter2 = List.of(1,2,3).iterator(); iter.hasNext(); ) { 14. bar(iter2.next()); 15. } 16. Which loop incurs a compile time error?

Options

  • AThe loop starting line 11
  • BThe loop starting line 7
  • CThe loop starting line 14
  • DThe loop starting line 3

How the community answered

(47 responses)
  • A
    74% (35)
  • B
    6% (3)
  • C
    4% (2)
  • D
    15% (7)

Explanation

Option A is correct because the for loop on line 10 declares Iterator iter in its initializer - but iter was already declared on line 1 in the same enclosing scope. Java does not allow a local variable to be re-declared in the same scope (or a nested scope within the same method), so this is a duplicate variable compile-time error.

Why the distractors are wrong:

  • D (line 3) and B (line 7): The while loops use iter and iter2 that were previously declared - they reference existing variables rather than declaring new ones, so no compile error occurs. (The loop at line 7 won't execute since iter is already exhausted, but that's a runtime behavior issue, not a compile error.)
  • C (line 14): The for loop on line 13 declares Iterator iter2, but the condition iter.hasNext() still refers to the iter from line 1, which remains in scope - no variable conflict.

Memory tip: Think of it as the "for-init is not a free pass" rule - declaring a variable in a for initializer (for (Type x = ...;)) follows the exact same scoping rules as any other local variable declaration. If that name already exists in the enclosing method scope, it's a duplicate declaration error, just as if you'd written Type x = ...; as a regular statement.

Topics

#variable scoping#for-loop initialization#iterator lifecycle#compile-time errors

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice