Challenge - 5 Problems
Switch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of switch with fall-through
What is the output of this Java code snippet?
Java
int x = 2; switch (x) { case 1: System.out.print("One "); case 2: System.out.print("Two "); case 3: System.out.print("Three "); break; default: System.out.print("Default "); }
Attempts:
2 left
💡 Hint
Remember that switch cases fall through unless you use break.
✗ Incorrect
Since x is 2, execution starts at case 2 and continues through case 3 until break. So it prints "Two Three ".
❓ Predict Output
intermediate2:00remaining
If-else equivalent output
What is the output of this if-else code equivalent to the previous switch?
Java
int x = 2; if (x == 1) { System.out.print("One "); } else if (x == 2) { System.out.print("Two "); } else if (x == 3) { System.out.print("Three "); } else { System.out.print("Default "); }
Attempts:
2 left
💡 Hint
If-else does not fall through cases.
✗ Incorrect
The if-else checks conditions one by one and executes only the matching block, so only "Two " is printed.
🧠 Conceptual
advanced2:00remaining
Switch expression with yield
What is the value of variable result after this Java switch expression runs?
Java
int x = 3; String result = switch (x) { case 1 -> "One"; case 2 -> "Two"; case 3 -> { yield "Three"; } default -> "Default"; }; System.out.print(result);
Attempts:
2 left
💡 Hint
Switch expressions use yield to return values from blocks.
✗ Incorrect
For x=3, the case 3 block yields "Three", so result is "Three".
❓ Predict Output
advanced2:00remaining
Switch with multiple labels output
What does this code print?
Java
int day = 5; switch (day) { case 1, 2, 3 -> System.out.print("Start"); case 4, 5, 6 -> System.out.print("Middle"); case 7 -> System.out.print("End"); default -> System.out.print("Unknown"); }
Attempts:
2 left
💡 Hint
Multiple labels can be combined with commas in switch cases.
✗ Incorrect
Day 5 matches case 4,5,6 so it prints "Middle".
❓ Predict Output
expert2:00remaining
Switch vs if with null value
What happens when this code runs?
Java
String s = null; switch (s) { case "a" -> System.out.print("A"); case "b" -> System.out.print("B"); default -> System.out.print("Default"); } if (s == null) { System.out.print("Null"); } else if (s.equals("a")) { System.out.print("A"); } else { System.out.print("Other"); }
Attempts:
2 left
💡 Hint
Switch on null reference causes an exception.
✗ Incorrect
Switch on a null String throws NullPointerException, but the if-else handles null safely.