"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Understanding Pattern Matching in Java

Understanding Pattern Matching in Java

Published on 2024-07-31
Browse:493

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

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

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.

Release Statement This article is reproduced at: https://dev.to/adaumircosta/understanding-pattern-matching-in-java-3f0k?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3