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…
Question
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)- A74% (35)
- B6% (3)
- C4% (2)
- D15% (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
whileloops useiteranditer2that 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 sinceiteris already exhausted, but that's a runtime behavior issue, not a compile error.) - C (line 14): The
forloop on line 13 declaresIterator iter2, but the conditioniter.hasNext()still refers to theiterfrom 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
Community Discussion
No community discussion yet for this question.