1Z0-819 · Question #16
Given: ``java public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println(i + ": " + args[i]); switch (args[i]) { case "one": continue; case "two": i = -1…
The correct answer is D. 0: one (infinite loop printing 0: one) 1: two... A java.lang.NullPointerException is thrown. Option D is correct because case "two" sets i = -1 before continue executes. The continue statement inside the switch targets the enclosing for-loop, which then runs its update expression (i++), bringing i back to 0. This permanently traps execution in a cycle: print 0: one →…
Question
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(i + ": " + args[i]);
switch (args[i]) {
case "one":
continue;
case "two":
i = -1;
continue;
default:
break;
}
}
}
executed with this command:
java Main one two three
What is the result?Options
- A0: one 1: two 2: three
- B0: one 1: two 2: three
- CThe compilation fails.
- D0: one (infinite loop printing 0: one) 1: two... A java.lang.NullPointerException is thrown.
- EA java.lang.NullPointerException is thrown.
How the community answered
(45 responses)- A2% (1)
- B7% (3)
- C11% (5)
- D78% (35)
- E2% (1)
Explanation
Option D is correct because case "two" sets i = -1 before continue executes. The continue statement inside the switch targets the enclosing for-loop, which then runs its update expression (i++), bringing i back to 0. This permanently traps execution in a cycle: print 0: one → hit continue (i→1) → print 1: two → set i=-1, hit continue (i→0) → repeat forever, never reaching index 2 ("three").
Why the distractors fail:
- A/B (printing all three): The loop never reaches
args[2]because i resets to 0 before it can reach 2. - C (compilation fails): Switch-on-String is valid since Java 7, and
continueinside a switch nested in a loop is legal - it targets the loop. - E (NullPointerException): No NPE occurs;
ionly ever takes values 0 or 1, both valid indices, so no out-of-bounds or null access happens.
Memory tip: Think of continue as a "jump to the top of the nearest loop" - it bypasses any remaining switch/block code but still runs the for-loop's update (i++). Whenever you see i = -1; continue inside a for-loop, read it as "reset i to 0 next iteration" - a classic infinite-loop trap on Java exams.
Topics
Community Discussion
No community discussion yet for this question.