• Uncategorised

Advanced Pattern Matching in Java: Handling Null, Case Sensitivity, and Instance Checks

In JDK 21, pattern matching was introduced in Java. Here’s an example demonstrating pattern matching in a switch statement using JDK 21.In this example, we have a switch statement that matches the given country with predefined patterns. Depending on the matched pattern, it prints the corresponding region or “Unknown” if no match is found.

public class CountryMatcher {
    public static void main(String[] args) {
        String country = "Nepal";
        switch (country) {
            case "India", "Pakistan" -> System.out.println("South Asia");
            case "Nepal", "Mauritius", "Seychelles", "Sri Lanka" -> System.out.println("Other countries");
            default -> System.out.println("Unknown");
        }
    }
}

Pattern matching with NULL. Before Java 21, switch statements would throw a NullPointerException if the selector expression was null. Pattern matching allows a dedicated case null clause to handle this scenario gracefully.

Object obj = null;
switch (obj) {
    case null:
        System.out.println("The object is null.");
        break;
    default:
        System.out.println("The object is not null.");
}

Pattern Matching With Primitive Types

int number = 10;
switch (number) {
    case 10:
        System.out.println("The number is 10.");
        break;
    case 20:
        System.out.println("The number is 20.");
        break;
    case 30:
        System.out.println("The number is 30.");
        break;
    default:
        System.out.println("The number is something else.");
}

Pattern Matching With instanceof. Combines type checking and casting in a single expression

if (object instanceof String str) {
    System.out.println("The string is: " + str);
} else if (object instanceof Integer num) {
    System.out.println("The number is: " + num);
} else {
    System.out.println("Unknown object type");
}

Pattern Matching With Switch Statements

public static String getAnimalSound(Animal animal) {
    return switch (animal) {
        case Dog dog -> "woof";
        case Cat cat -> "meow";
        case Bird bird -> "chirp";
        case null -> "No animal found!";
        default -> "Unknown animal sound";
    };
}

You may also like...