0
0
Javaprogramming~20 mins

Switch statement in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Switch Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
AString: 123
BInteger: 123
CUnknown
DCompilation error
Attempts:
2 left
💡 Hint
Remember that the switch matches the first compatible case.
Predict Output
intermediate
2: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);
AWednesday
BInvalid
CCompilation error
Dnull
Attempts:
2 left
💡 Hint
The yield keyword returns a value from a block in a switch expression.
Predict Output
advanced
2: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");
}
ALow
BMedium
CLow Medium
DLow Medium High
Attempts:
2 left
💡 Hint
Without break after case 1,2,3, execution falls through to case 4.
Predict Output
advanced
2: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);
ACompilation error due to missing default
BSquare with side 2.0
CRuntime exception
DCircle with radius 2.0
Attempts:
2 left
💡 Hint
Sealed interfaces allow exhaustive switch without default.
Predict Output
expert
2: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);
ACompilation error: 'case null' not allowed
BOther
CNull value
DRuntime NullPointerException
Attempts:
2 left
💡 Hint
Java switch does not allow 'case null' labels.