[go: up one dir, main page]

DEV Community

Understanding Pattern Matching in Java

Pattern matching is a powerful feature introduced in Java that allows you to simplify and enhance the readability of your code. Initially introduced in Java 14 for instanceof checks and extended in later versions, pattern matching enables more expressive and concise code by reducing boilerplate.

What is Pattern Matching?

Pattern matching allows you to extract components from objects and apply certain conditions in a concise manner. It is a feature that checks a value against a pattern and, if the match is successful, binds variables from the pattern.

Benefits of Pattern Matching

  1. Concise Code: Reduces boilerplate code, making your programs shorter and easier to read.
  2. Improved Readability: Enhances the clarity of your code by making the structure more apparent.
  3. Type Safety: Ensures that variables are correctly typed, reducing the likelihood of runtime errors.

Pattern Matching with instanceof

One of the most common uses of pattern matching is with the instanceof operator. Here’s an example:

public class PatternMatchingExample {
    public static void main(String[] args) {
        Object obj = "Hello, World!";

        if (obj instanceof String s) {
            System.out.println("The string is: " + s);
        } else {
            System.out.println("Not a string");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the instanceof operator not only checks if obj is a String but also casts it to a String and binds it to the variable s in a single step.

Pattern Matching with Switch Expressions

Pattern matching is also used with switch expressions, enhancing their power and flexibility. Here’s an example using sealed classes:

public sealed class Shape permits Circle, Rectangle, Square {}

public final class Circle extends Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double radius() { return radius; }
}

public final class Rectangle extends Shape {
    private final double width, height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double width() { return width; }
    public double height() { return height; }
}

public final class Square extends Shape {
    private final double side;

    public Square(double side) {
        this.side = side;
    }

    public double side() { return side; }
}

public class PatternMatchingWithSwitch {
    public static void main(String[] args) {
        Shape shape = new Circle(5);

        String result = switch (shape) {
            case Circle c -> "Circle with radius " + c.radius();
            case Rectangle r -> "Rectangle with width " + r.width() + " and height " + r.height();
            case Square s -> "Square with side " + s.side();
        };

        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the switch expression uses pattern matching to destructure the Shape objects and extract relevant data.

Conclusion

Pattern matching in Java brings a new level of expressiveness and simplicity to your code. By reducing boilerplate and enhancing readability, it allows you to write cleaner and more maintainable programs. Whether you are working with complex data structures or simply trying to streamline your type checks, pattern matching is a valuable tool in your Java toolkit.

Top comments (2)

Collapse
 
chrisco484 profile image
Christopher Colemani

I'm still mainly using Java 8 (mainly to keep our platform and libraries compatible with corporate clients who are holding out on Java 8 for some time to come) but the more I see of these really nice and helpful improvements to the Java language over time the more I'm tempted to move up to a later version ;)

Pattern matching is very nice indeed!

The switch example is very nice, however I do try to write polymorphic code which means I can usually eliminate the need for switch statements in many scenarios by invoking a base/super class method on a reference to the base/super class which then invokes the type specific implementation of that method when called.

But, yes, as an example of the new switch statement's capabilities - that is very neat!

Collapse
 
adaumircosta profile image
Adaumir Paixão Victor da Costa

Good point @chrisco484