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.

JavaForm Validation

Code

snippet
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));
    }
}

How it works

Pattern Matching for Switch reduces to the classes PatternMatchingSwitch, Shape, Circle and Rectangle and the functions area, describe and main.

Using it

The main signature reads static double area(Shape shape)

Running the file prints labeled results such as Circle area:, Rectangle area:, Triangle area: — each operation’s effect is visible in the output.

The entry point wires area and describe together — run it once and the whole demo flows.

Key statements

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();
};

Interactive Tools for This Topic

FAQ

What does Pattern Matching for Switch print when run?
Invoke the file as-is — the `Circle area:`, `Rectangle area:`, `Triangle area:` prefixes identify which step printed each line.