switch
Modern Java switch is an EXPRESSION that returns a value. Arrow syntax avoids fall-through; multiple labels per case; pattern matching (Java 21+) destructures records and types.
Switch expression + pattern matching
EXAMPLE
public class Demo {
sealed interface Shape permits Circle, Rect, Triangle {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
record Triangle(double base, double height) implements Shape {}
public static void main(String[] args) {
var day = "Sat";
// 1) Switch EXPRESSION — returns a value, no break needed
var kind = switch (day) {
case "Sat", "Sun" -> "weekend";
case "Mon", "Tue", "Wed", "Thu", "Fri" -> "weekday";
default -> "unknown";
};
System.out.println(kind);
// 2) Block bodies + yield
int score = 85;
String grade = switch (score / 10) {
case 10, 9 -> "A";
case 8 -> {
System.out.println("close to A");
yield "B";
}
case 7 -> "C";
default -> "F";
};
// 3) Pattern matching — destructure records (Java 21+)
Shape shape = new Circle(2.0);
double area = switch (shape) {
case Circle c -> Math.PI * c.r() * c.r();
case Rect r -> r.w() * r.h();
case Triangle t when t.height() > 0 -> 0.5 * t.base() * t.height();
case Triangle t -> 0;
};
System.out.printf("area %.2f%n", area);
// 4) Sealed types — compiler enforces exhaustiveness
// If you add a new permits-class without updating this switch,
// the compile FAILS — impossible to forget.
}
}
Why it matters
Switch expressions on sealed types is THE pattern for modern Java domain logic. The compiler proves you handled every case — impossible states become impossible.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
String day = "SAT";
String kind = switch (day) {
case "SAT", "SUN" -> "weekend";
default -> "weekday";
};
System.out.println(kind);
Try it Yourself »
Discussion
Loading…