5. Switch Expressions
Switch expressions (Java 14+) replace the error-prone fall-through statement form with arrow labels, a yield keyword, and the ability to return a value โ eliminating most break bugs.
Explanation
Classic switch statements have fall-through semantics (a missing break silently continues into the next case) and cannot return a value directly. Switch expressions (JEP 361, standard since Java 14) fix both problems.
Arrow labels (case X -> ...) do not fall through. To return a value from a multi-statement arm, use yield. Switch expressions must be exhaustive โ the compiler enforces that all possible values are handled, either with explicit cases or a default.
When combined with sealed classes or enums (Java 17+) and pattern matching (Java 21+), switch expressions become a powerful tool for algebraic data processing with full compiler-enforced exhaustiveness.
Example
public class SwitchExpressions {
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double base, double h) implements Shape {}
static double area(Shape s) {
// Pattern matching switch โ exhaustive over sealed type
return switch (s) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.w() * r.h();
case Triangle t -> 0.5 * t.base() * t.h();
};
}
public static void main(String[] args) {
// Simple value switch with arrow labels (no fall-through)
int day = 3;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
System.out.println(name); // Wednesday
// yield for multi-statement arm
String label = switch (day) {
case 1, 2, 3, 4, 5 -> {
String d = name.toLowerCase();
yield "Weekday: " + d;
}
default -> "Weekend";
};
System.out.println(label);
System.out.printf("Circle area: %.2f%n", area(new Circle(5)));
}
}Sources
- https://openjdk.org/jeps/361 โ JEP 361: Switch Expressions (standard)
- https://docs.oracle.com/en/java/javase/21/language/switch-expressions.html โ Switch expressions guide