Switch Statements & Expressions
Prerequisites: Conditionals
Modern Java (14+) prefers the switch expression form — no
break needed, and it can produce a value directly:
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown";
};
System.out.println(name); // Wednesday
The older statement form still works, but requires an explicit
break in each branch to avoid fall-through (execution
continuing into the next case):
switch (day) {
case 1:
System.out.println("Monday");
break;
default:
System.out.println("Unknown");
}
Common mistakes
- Forgetting
breakin the older statement form — execution falls through into the nextcaseinstead of stopping. The arrow-form->avoids this entirely.