Java 21 Pattern Matching for Switch Example

Java has been constantly evolving to meet the demands of modern programming. With the release of Java 21, a notable feature called Java 21 Pattern Matching for Switch has been introduced. In this article, we’ll explore what this feature is all about, how it works, and see some real-world examples to understand its practical applications.

Introducing Java 21’s Pattern Matching for Switch

Java 21 brings a significant improvement known as Pattern Matching for Switch, which revolutionizes the way we handle switch statements. This feature makes code selection more straightforward by letting us use patterns in case labels. It not only improves code readability but also reduces redundancy and simplifies complex switch statements.

How Pattern Matching Improves Switch Statements

Pattern Matching allows developers to utilize patterns in case labels, making it easier to match and extract components from objects. This eliminates the need for casting and repetitive instanceof checks, resulting in cleaner and more efficient code. Let’s dive into some practical examples to understand how Pattern Matching functions in real-world scenarios.

Practical Examples

Example 1: Matching a Specific Value

Consider a scenario where you need to categorize shapes based on their names. In traditional switch statements, you might do the following:

switch (shape) {
    case "circle":
        System.out.println("Handling circle logic");
        break;
    case "rectangle":
        System.out.println("Handling rectangle logic");
        break;
    case "triangle":
        System.out.println("Handling triangle logic");
        break;
    default:
        // Handle other cases
}

With Pattern Matching, you can simplify above code:

switch (shape) {
    case "circle" -> {
    	 System.out.println("Handling circle logic");
    }
    case "rectangle" -> {
        System.out.println("Handling rectangle logic");
    }
    case "triangle" -> {
       System.out.println("Handling triangle logic");
    }
    default -> {
        // Handle other cases
    }
}

Pattern Matching allows for a more concise and readable switch statement.

Example 2: Matching Complex Objects

Pattern Matching can also simplify code when dealing with complex objects. Suppose you have a list of vehicles, and you want to perform specific actions based on the vehicle type:

for (Object v : vehicles) {
    if (v instanceof Car) {
        Car car = (Car) v;
        //car logic
    } else if (v instanceof Scooter) {
        Scooter scooter = (Scooter) v;
        //scooter logic
    } else if (v instanceof Jeep) {
        Jeep jeep = (Jeep) v;
        //jeep logic
    }
}

The code above can be rewritten using Pattern Matching.

for (Object v : vehicles) {

    return switch (v) {
        case Car car -> {
            //car logic
        }
        case Scooter scooter -> {
            //scooter logic
        }
        case Jeep jeep -> {
            //jeep logic
        }
    }
}

Pattern Matching simplifies the code and eliminates the need for explicit casting.

Example 3: Java 21 – Handling Null Cases in Switch Statements

Before Java 21, switch statements and expressions posed a risk of throwing NullPointerExceptions when the selector expression was evaluated as null.

public void handleGreetings(String s) {
 // If 's' is null and we don't handle it, it will result in a NullPointerException.
    if (s == null) {
        System.out.println("No message available.");
        return;
    }
    switch (s) {
        case "Hello", "Hi" -> System.out.println("Greetings!");
        case "Bye" -> System.out.println("Goodbye!");
        default -> System.out.println("Same to you!");
    }
}

Java 21 Introduces a New Null Case Label. above code can rewritten like this

public void handleGreetingsInJava21(String s) {
    switch (s) {
        case null           -> System.out.println("No message available.");
        case "Hello", "Hi" -> System.out.println("Hello there!");
        case "Bye"         -> System.out.println("Goodbye!");
        default            -> System.out.println("Same to you!");
    }
}

Example 4: Java 21 Pattern Matching with Guards

In Java 21, pattern case labels can apply to multiple values, leading to conditional code on the right-hand side of a switch rule. However, we can now simplify our code using guards, allowing ‘when’ clauses in switch blocks to specify guards to pattern case labels.

Before Java 21.

public void testInput(String response) {

    switch (response) {
        case null -> System.out.println("No message available.");
        case String s when s.equalsIgnoreCase("MAYBE") -> {
            System.out.println("Not sure, please decide.");
        }
        case String s when s.equalsIgnoreCase("EXIT") -> {
            System.out.println("Exiting now.");
        }
        default -> System.out.println("Please retry.");
    }
}

Using Java 21 – Simplified Code

public void test21Input(String response) {

    switch (response) {
        case null -> System.out.println("No message available.");
        case String s when s.equalsIgnoreCase("MAYBE") -> {
            System.out.println("Not sure, please decide.");
        }
        case String s when s.equalsIgnoreCase("EXIT") -> {
            System.out.println("Exiting now.");
        }
        default -> System.out.println("Please retry.");
    }
}

With Java 21’s new features, your code becomes more concise and easier to read, making pattern matching a powerful tool in Java programming toolkit.

Benefits of Java 21

  1. Improved code readability
  2. Reduced boilerplate code
  3. Simplified complex switch statements
  4. Enhanced developer productivity

In conclusion, Java 21 Pattern Matching for Switch is a valuable addition to the Java language, making code selection more straightforward and efficient. By using patterns in switch statements, developers can write cleaner, more concise, and more readable code, ultimately improving software quality and maintainability.

For additional information on pattern matching in Java, you can visit the following link: Pattern Matching (JEP 441) – OpenJDK. This link provides detailed information about the Java Enhancement Proposal (JEP) for pattern matching in Java.

Leave a Comment