Switch pattern matching — combine type checking and destructuring in switch expressions, eliminating verbose instanceof chains.
1public static String format(Object obj) {2 return switch (obj) {3 case Integer i -> "Integer: " + i;4 case String s when s.length() > 5 -> "Long string: " + s;5 case String s -> "String: " + s;6 case null -> "null";7 default -> "Unknown: " + obj;8 };9}1011// Pattern matching with sealed classes12sealed interface Shape {}13record Circle(double radius) implements Shape {}14record Rectangle(double w, double h) implements Shape {}1516double area(Shape shape) {17 return switch (shape) {18 case Circle c -> Math.PI * c.radius() * c.radius();19 case Rectangle r -> r.w() * r.h();20 // No default needed — sealed class has exhaustive types21 };22}2324// Nested pattern matching25record Wrapper(Object value) {}2627string describe(Wrapper w) {28 return switch (w) {29 case Wrapper(Integer i) -> "Integer wrapper: " + i;30 case Wrapper(String s) -> "String wrapper: " + s;31 case Wrapper(null) -> "Empty wrapper";32 case Wrapper(var v) -> "Other wrapper: " + v;33 };34}
Benefits:
when.