Challenge - 5 Problems
Switch Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of switch with pattern matching
What is the output of the following Java code using switch with pattern matching?
Java
Object obj = 123; String result = switch (obj) { case Integer i -> "Integer: " + i; case String s -> "String: " + s; default -> "Unknown"; }; System.out.println(result);
Attempts:
2 left
💡 Hint
Remember that the switch matches the first compatible case.
✗ Incorrect
The object is an Integer with value 123, so the case Integer i matches and returns "Integer: 123".
❓ Predict Output
intermediate2:00remaining
Switch expression with yield
What will be printed by this Java code using switch expression with yield?
Java
int day = 3; String dayName = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> { yield "Wednesday"; } default -> "Invalid"; }; System.out.println(dayName);
Attempts:
2 left
💡 Hint
The yield keyword returns a value from a block in a switch expression.
✗ Incorrect
For day = 3, the switch block uses yield to return "Wednesday".
❓ Predict Output
advanced2:00remaining
Switch with multiple labels and fall-through
What is the output of this Java switch statement?
Java
int num = 2; switch (num) { case 1, 2, 3: System.out.print("Low"); case 4: System.out.print(" Medium"); break; default: System.out.print(" High"); }
Attempts:
2 left
💡 Hint
Without break after case 1,2,3, execution falls through to case 4.
✗ Incorrect
Case 2 matches, prints "Low", then falls through to case 4, prints " Medium", then breaks.
❓ Predict Output
advanced2:00remaining
Switch expression with sealed classes
Given sealed classes and a switch expression, what is the output?
Java
sealed interface Shape permits Circle, Square {} record Circle(double radius) implements Shape {} record Square(double side) implements Shape {} Shape shape = new Circle(2.0); String desc = switch (shape) { case Circle c -> "Circle with radius " + c.radius(); case Square s -> "Square with side " + s.side(); }; System.out.println(desc);
Attempts:
2 left
💡 Hint
Sealed interfaces allow exhaustive switch without default.
✗ Incorrect
The shape is a Circle with radius 2.0, so the first case matches and returns the description.
❓ Predict Output
expert2:00remaining
Switch expression with null and pattern matching
What happens when this Java code runs?
Java
Object obj = null; String result = switch (obj) { case String s -> "String: " + s; case null -> "Null value"; default -> "Other"; }; System.out.println(result);
Attempts:
2 left
💡 Hint
Java switch does not allow 'case null' labels.
✗ Incorrect
Java switch expressions do not support 'case null' labels, so this code does not compile.