Java switch without breaks (fall-through) — compute final j value. public class Test { public static void main(String args[]) { int i = 1, j = 0; switch(i) { case 2: j += 6; case 4: j += 1; default: j += 2; case 0: j += 4; } System.out.println("j = " + j); } } What is printed?

Java Programming Flow Control Difficulty: Easy
Choose an option
  • A
    j = 0
  • B
    j = 2
  • C
    j = 4
  • D
    j = 6

Answer

Correct Answer: j = 6

Explanation

Introduction / Context:This MCQ reinforces switch fall-through semantics in Java when break statements are omitted. You must determine which labels execute when no case matches i=1 until default is reached.

Given Data / Assumptions:

  • Switch expression is i = 1.
  • Cases present: 2, 4, default, and 0, with no breaks.
  • j starts at 0.

Concept / Approach:If no case matches, execution begins at default and proceeds downward until the switch block ends (fall-through). Therefore, default and all following case bodies execute sequentially.

Step-by-Step Solution:

No match for case 2 or case 4.Hit default: j += 2 → j = 2.Fall through to case 0: j += 4 → j = 6.End of switch; print "j = 6".

Verification / Alternative check:Add breaks after default or case 0 to change the result; with current code, both default and case 0 run.

Why Other Options Are Wrong:

  • "0", "2", or "4" ignore the second addition from case 0 or the first addition at default.

Common Pitfalls:Expecting that default stops execution; it does not without a break.

Final Answer:j = 6

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