Phase 5 of 20 · Topic 5.3

Pattern Matching for Switch (Java 21+)

1Concept

Java 21 finalized Pattern Matching for Switch (JEP 441). Switch statements and expressions can now test against object types directly, bind variables automatically, support guarded `when` expressions, and safely handle `case null`.

2Architecture Diagram

Object obj ---> switch (obj) {
                  case Integer i when i > 100 -> "Large Integer";
                  case String s               -> "Text of length " + s.length();
                  case null                   -> "Null received";
                }

3Code Example

Core Java
public class PatternMatchingSwitchDemo {
    public static void main(String[] args) {
        Object[] items = {"Microservices Architecture", 404, 3.14159, null};

        for (Object item : items) {
            String formatted = switch (item) {
                case null -> "Received Null Reference";
                case Integer code when code >= 400 -> "HTTP Error Code: " + code;
                case Integer code -> "HTTP Success Code: " + code;
                case String text -> "String Payload (" + text.length() + " chars): " + text;
                case Double d -> String.format("Precision Decimal: %.2f", d);
                default -> "Unknown Object: " + item;
            };
            System.out.println(formatted);
        }
    }
}

4Expected Output

String Payload (26 chars): Microservices Architecture
HTTP Error Code: 404
Precision Decimal: 3.14
Received Null Reference

5Key Takeaways

  • Subtype patterns must appear before supertype patterns (e.g. Integer before Number).
  • `case null` is now explicitly supported in switch, preventing NullPointerExceptions.
  • Guarded patterns using `when` allow adding arbitrary boolean expressions to type checks.