nerdexam
Oracle

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 →…

Controlling Program Flow

Question

Given:
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)
  • A
    2% (1)
  • B
    7% (3)
  • C
    11% (5)
  • D
    78% (35)
  • E
    2% (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 continue inside a switch nested in a loop is legal - it targets the loop.
  • E (NullPointerException): No NPE occurs; i only 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

#loop control flow#switch statements#continue behavior#for loop increment order

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice