Java Pattern Matching for instanceof

1. Introduction

This blog post focuses on Java's Pattern Matching for instanceof, a feature introduced in Java 16 as a preview and later finalized. This feature simplifies the process of type checking and casting, enhancing code readability and reducing boilerplate.

Definition

Pattern Matching for instanceof extends the instanceof operator in Java. It allows you to automatically cast a variable to a target type if it passes an instanceof check, removing the need for explicit casting.

2. Program Steps

1. Create a scenario where traditional type checking and casting are used.

2. Rewrite the scenario using Pattern Matching for instanceof.

3. Compare the readability and simplicity of the new approach.

3. Code Program

public class PatternMatchingInstanceof {

    // Traditional approach without pattern matching
    public static String getFormattedObjectTraditional(Object obj) {
        if (obj instanceof String) {
            String str = (String) obj;
            return "String: " + str;
        } else if (obj instanceof Integer) {
            Integer num = (Integer) obj;
            return "Integer: " + num;
        } else {
            return "Unknown Type";
        }
    }

    // Approach using pattern matching for instanceof
    public static String getFormattedObjectPatternMatching(Object obj) {
        if (obj instanceof String str) {
            return "String: " + str;
        } else if (obj instanceof Integer num) {
            return "Integer: " + num;
        } else {
            return "Unknown Type";
        }
    }

    public static void main(String[] args) {
        System.out.println(getFormattedObjectTraditional("Hello"));
        System.out.println(getFormattedObjectPatternMatching(123));
    }
}

Output:

String: Hello
Integer: 123

Explanation:

1. Two methods getFormattedObjectTraditional and getFormattedObjectPatternMatching demonstrate type checking and casting.

2. The traditional method uses the instanceof operator followed by an explicit cast.

3. The pattern matching method utilizes the enhanced instanceof operator, which performs the check and the cast in one step.

4. In the main method, both approaches are used to format different types of objects.

5. The output shows identical results, but the pattern matching approach is more concise and readable, reducing the potential for errors.


Comments