In Java, analyze switch fall-through within a for loop and predict the exact output sequence. for (int i = 0; i < 3; i++) { switch (i) { case 0: break; case 1: System.out.print("one "); case 2: System.out.print("two "); case 3: System.out.print("three "); } } System.out.println("done");

Difficulty: Medium

Correct Answer: one two three two three done

Explanation:

Introduction / Context:This problem checks understanding of Java switch fall-through and its interaction with a for loop. Without break statements, control falls through to subsequent case labels, executing their statements even if the matched constant differs.

Given Data / Assumptions:

  • i takes values 0, 1, 2.
  • Only case 0 contains a break; others do not.
  • Print statements occur in case 1, case 2, and case 3.

Concept / Approach:For each loop iteration, identify the matched case and then follow fall-through execution to the end of the switch (unless a break is encountered). Then concatenate the outputs across iterations.

Step-by-Step Solution:i = 0 ⇒ case 0 hits break immediately ⇒ prints nothing.i = 1 ⇒ enters case 1 ⇒ prints "one ", then falls through to case 2 and prints "two ", then falls through to case 3 and prints "three ".i = 2 ⇒ enters case 2 ⇒ prints "two ", falls through to case 3 and prints "three ".Finally, println("done") appends "done" with a newline.

Verification / Alternative check:Add explicit break after each case to see the difference, or reorder cases to observe fall-through behavior.

Why Other Options Are Wrong:They omit some fall-through prints or add impossible ones given the loop bounds.

Common Pitfalls:Assuming a switch stops after one matching case without a break; forgetting that fall-through continues to all subsequent cases.

Final Answer:one two three two three done

More Questions from Flow Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion