Pattern Matching for Switch
Uses Java pattern matching with switch expressions and type patterns to handle different object types concisely without explicit casts or instanceof checks.
Code
public class PatternMatchingSwitch {
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Triangle(double base, double height) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Triangle t -> 0.5 * t.base() * t.height();
};
}
static String describe(Object obj) {
return switch (obj) {
case null -> "null";
case Integer i when i > 0 -> "positive integer: " + i;
case Integer i -> "non-positive integer: " + i;
case String s when s.length() > 10 -> "long string";
case String s -> "short string: " + s;
case int[] arr -> "int array of length " + arr.length;
default -> "unknown type: " + obj.getClass().getSimpleName();
};
}
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rect = new Rectangle(4, 6);
Shape tri = new Triangle(3, 8);
System.out.println("Circle area: " + area(circle));
System.out.println("Rectangle area: " + area(rect));
System.out.println("Triangle area: " + area(tri));
System.out.println(describe(42));
System.out.println(describe(-5));
System.out.println(describe("hello"));
System.out.println(describe("a very long string here"));
System.out.println(describe(new int[]{1, 2, 3}));
System.out.println(describe(null));
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.