Skip to content
Java

Pattern Matching

instanceof pattern matching.

By EZ4Code Team
pattern-matchingtype

Code

// instanceof pattern matching (Java 16+)
Object obj = "Hello World";
if (obj instanceof String s) {
    System.out.println(s.length());
    System.out.println(s.toUpperCase());
}

// switch pattern matching (Java 21+)
String describe(Object o) {
    return switch (o) {
        case Integer i -> "Integer: " + i;
        case String s -> "String: " + s;
        case null -> "null";
        case int[] arr -> "Array of length " + arr.length;
        default -> "Unknown: " + o;
    };
}

// Pattern with guard
String check(Object o) {
    return switch (o) {
        case String s when s.length() > 5 -> "Long string";
        case String s -> "Short string";
        default -> "Not a string";
    };
}

Explanation

Pattern matching simplifies type checking and conversion; switch pattern matching supports type patterns and guard conditions.

More Java Snippets