Careeroza
Switch Expressions
Arrow Syntax (Java 14+)
Modern Java has switch expressions with case X ->. No fall-through, no break, several labels per case, and the switch can return a value.
Example
public class Main {
public static void main(String[] args) {
int day = 6;
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid day";
};
System.out.println(type);
int month = 2;
int days = switch (month) {
case 4, 6, 9, 11 -> 30;
case 2 -> 28;
default -> 31;
};
System.out.println("Days: " + days);
}
}Output
Weekend Days: 28
Blocks and yield
Example
When a case needs several statements, use a block and return the value with yield.
public class Main {
public static void main(String[] args) {
String plan = "GOLD";
double amount = 1000;
double payable = switch (plan) {
case "SILVER" -> amount * 0.95;
case "GOLD" -> {
double discount = amount * 0.10;
System.out.println("Gold discount: " + discount);
yield amount - discount;
}
default -> amount;
};
System.out.println("Payable: " + payable);
}
}Output
Gold discount: 100.0 Payable: 900.0
Classic vs Expression
Classic case X: | Arrow case X -> | |
|---|---|---|
| Fall-through | yes, needs break | no |
| Multiple labels | stack cases | case 1, 2, 3 -> |
| Returns a value | no | yes (as an expression) |
| Exhaustive check | no | yes when used as an expression (needs default or all enum values) |
Tip: Prefer arrow-style switches in new code. They are shorter and avoid the missing-break bug.