Q65: How does Pattern Matching for switch work (Java 21+)?

Pattern Matching for switch allows inspecting object types directly within switch expressions, binding variables automatically, using guard clauses (when), and handling null cases cleanly.

Pattern Matching for Switch with Guard Clause
public static String formatValue(Object obj) {
    return switch (obj) {
        case Integer i -> String.format("Int: %d", i);
        case String s when s.length() > 5 -> "Long String: " + s.toUpperCase();
        case String s -> "Short String: " + s;
        case null -> "Null Value";
        default -> obj.toString();
    };
}
💡 Direct type matching with automatic variable casting and guard clause conditions.
Key Takeaways
  • Type pattern matching inside switch expressions.
  • Supports guard clauses using when condition filters.
Knowledge Check

Which keyword introduces additional conditional filters (guard clauses) inside pattern matching switch cases?