Java Switch Statement — Classic & Modern Switch Expressions
When you need to compare a variable against many specific values, a switch statement is cleaner than a long if-else chain.
Classic Switch Statement
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
break;
}
// Output: Wednesday
Rules
- The expression must be
int,byte,short,char,String, or anenum. - Each
casemust be a constant (literal orfinalvariable). breakexits the switch. Without it, execution falls through to the next case.defaulthandles all unmatched values (optional but recommended).
The Fall-Through Trap
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
// no break — falls through!
case 2:
System.out.println("Tuesday");
// no break — falls through!
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other");
}
Output:
Tuesday
Wednesday
⚠️ Always include
breakunless fall-through is intentional.
Intentional Fall-Through
Sometimes useful for grouping:
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
}
Switch with Strings
String command = "start";
switch (command) {
case "start":
System.out.println("Starting...");
break;
case "stop":
System.out.println("Stopping...");
break;
case "restart":
System.out.println("Restarting...");
break;
default:
System.out.println("Unknown command");
}
String comparison in switch is case-sensitive. Convert to lowercase first if needed:
command.toLowerCase().
Enhanced Switch Expression (Java 14+)
Modern Java offers a cleaner syntax using arrow (->):
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> "Invalid";
};
System.out.println(dayName); // Wednesday
Benefits of Arrow Syntax
- No fall-through — no need for
break - Returns a value — it’s an expression, not just a statement
- Multiple labels per case:
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
Multi-Line Cases with yield
When a case needs more than one statement, use a block and yield:
String description = switch (day) {
case 1 -> "Monday — Start of the week";
case 5 -> {
System.out.println("Almost weekend!");
yield "Friday — TGIF!";
}
default -> "Regular day";
};
Switch with Enums
Switch works beautifully with enums:
enum Season { SPRING, SUMMER, FALL, WINTER }
Season season = Season.SUMMER;
String activity = switch (season) {
case SPRING -> "Gardening";
case SUMMER -> "Swimming";
case FALL -> "Hiking";
case WINTER -> "Skiing";
};
With enums, no
defaultis needed if all values are covered (the compiler checks).
Pattern Matching in Switch (Java 21+)
Java 21 introduced pattern matching for switch:
Object obj = "Hello";
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
case null -> "null";
default -> "Unknown: " + obj;
};
System.out.println(result); // String: Hello
Guarded Patterns
Object obj = 42;
String result = switch (obj) {
case Integer i when i > 0 -> "Positive integer: " + i;
case Integer i -> "Non-positive integer: " + i;
case String s -> "String: " + s;
default -> "Other";
};
When to Use Switch vs If-Else
| Use Switch | Use If-Else |
|---|---|
| Comparing against specific values | Complex range conditions |
Variable is int, String, or enum |
Boolean expressions |
| Many cases to handle | 2-3 simple conditions |
| Readability matters | Conditions involve different variables |
Quick Exercises
- Write a switch that converts a month number (1-12) to its name.
- Rewrite the grading example from the
if-elsechapter using switch expressions. - Write a switch that takes a
charoperator (+,-,*,/) and performs the calculation.
Summary
| Feature | Classic Switch | Enhanced Switch (14+) |
|---|---|---|
| Syntax | case X: ... break; |
case X -> ...; |
| Fall-through | Yes (needs break) | No |
| Returns value | No | Yes (expression) |
| Multiple labels | Stacked cases | case 1, 2, 3 -> |
| Multi-line | Regular block | Block + yield |
What’s Next?
Decision-making is done. Now let’s learn loops — repeating actions — starting with the for loop: For Loop.