Pattern Matching — Switch (Java 21)
Type patterns in switch, guarded patterns, null handling, exhaustiveness with sealed types
- Write type-safe, exhaustive switch expressions over sealed hierarchies
- Add guards to switch arms with when clauses
- Safely handle null in switch without NullPointerException
A professional-quality reference covering Pattern Matching for Switch introduced in Java 21, with deep explanations, code examples, diagrams, performance analysis, and interview notes.
Table of Contents
- Prerequisites & Background
- What is Pattern Matching for Switch?
- Traditional Switch — A Recap
- Pattern Matching for Switch — Core Syntax
- Internal Working — How It Really Works
- Performance: Pattern Switch vs Classic Switch vs if-else
- Scope of Pattern Variables
- Pattern Matching with Inheritance
- Pattern Matching with Enums
- Null Handling in Pattern Switch
- Grouping of Patterns — What Is NOT Allowed
- Guarded Patterns — The
whenClause - Quick Reference Table
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. Prerequisites & Background
Before diving into Pattern Matching for Switch, you should be comfortable with two earlier Java features. This section makes the guide self-contained.
1.1 Pattern Matching for `instanceof` (Java 16)
Before Java 16, checking a type and then casting it required two steps:
1// Traditional — Java 15 and before2Object obj = "Hello";3
4if (obj instanceof String) {5 String s = (String) obj; // explicit cast required6 System.out.println(s.toUpperCase());7}Java 16 introduced pattern matching for instanceof:
1// Java 16+ — type check and cast in one step2Object obj = "Hello";3
4if (obj instanceof String s) {5 // 's' is automatically declared and type-cast here6 System.out.println(s.toUpperCase()); // HELLO7}Key rules of instanceof pattern matching:
- The variable (
s) is only in scope inside theifblock - Cannot use
||(OR) when declaring a pattern variable - Can use
&&(AND) to add extra conditions:if (obj instanceof String s && s.length() > 3) - The runtime checks
instanceoffirst; iffalse, the variable is never bound (noNullPointerException)
instanceof pattern matching. Understanding instanceof pattern matching first makes Switch patterns straightforward.1.2 Switch Statement vs Switch Expression (Java 14)
Java 14 introduced the switch expression (in addition to the classic switch statement), with two key improvements:
1// Classic switch statement (pre-Java 14)2int day = 2;3String result;4switch (day) {5 case 1:6 result = "Monday";7 break;8 case 2:9 result = "Tuesday";10 break;11 default:12 result = "Other";13}14
15// Switch expression (Java 14+) — arrow syntax16int day = 2;17String result = switch (day) {18 case 1 -> "Monday";19 case 2 -> "Tuesday";20 default -> "Other";21};22System.out.println(result); // Tuesdayyield keyword (Java 14+): Used inside a switch expression block to return a value:
1String result = switch (day) {2 case 1 -> "Monday";3 case 2 -> {4 System.out.println("Processing Tuesday...");5 yield "Tuesday"; // 'yield' returns the value from the block6 }7 default -> "Other";8};yield). It is a superset, not a replacement.2. What is Pattern Matching for Switch?
Overview
Pattern Matching for Switch is a Java 21 feature (finalized; it appeared as a preview in earlier versions) that extends the switch statement and expression to support object types as case labels — not just primitives, enums, and strings.
It allows you to match an object against multiple type patterns in a single switch block, eliminating chains of if (obj instanceof X) ... else if (obj instanceof Y) code.
Why This Feature Exists
The Problem Verbose Type-Checking
Consider a method that handles different subtypes of a sealed class or interface:
1// Java 20 and before — tedious and error-prone2static String describe(Object obj) {3 if (obj instanceof Integer i) {4 return "Integer: " + i;5 } else if (obj instanceof String s) {6 return "String: " + s;7 } else if (obj instanceof Double d) {8 return "Double: " + d;9 } else {10 return "Unknown";11 }12}This works but:
- Is verbose
- Doesn't guarantee exhaustiveness (you might miss a case)
- Doesn't read as cleanly as a
switch
The Solution Pattern Switch
1// Java 21 — clean, readable, exhaustive2static String describe(Object obj) {3 return switch (obj) {4 case Integer i -> "Integer: " + i;5 case String s -> "String: " + s;6 case Double d -> "Double: " + d;7 default -> "Unknown";8 };9}Definition
Pattern Matching for Switch
(Java 21) extends the switch construct to allow type patterns as case labels. Each case can declare a pattern variable that is automatically type-cast when the pattern matches, eliminating explicit casting. It supports all object types: classes, interfaces, abstract types, and wrapper types.
Java Version Timeline
| Java Version | Feature status |
|---|---|
| Java 14 | Switch expressions finalized |
| Java 16 | Pattern matching for instanceof finalized |
| Java 17–20 | Pattern matching for switch (preview) |
| Java 21 | Pattern matching for switch — finalized |
Supported Types Before and After Java 21
| Type | Classic Switch (pre-21) | Pattern Switch (Java 21) |
|---|---|---|
int, short, byte, char (primitives) | ✅ | ✅ |
Integer, Short, Byte, Character (wrappers) | ✅ | ✅ |
String | ✅ | ✅ |
enum | ✅ | ✅ |
| Classes | ❌ | ✅ |
| Interfaces | ❌ | ✅ |
| Abstract classes | ❌ | ✅ |
Object | ❌ | ✅ |
3. Traditional Switch A Recap
Understanding the traditional forms helps appreciate what Java 21 adds.
Statement Form (with `break`)
1int a = 2;2switch (a) {3 case 1:4 System.out.println("Monday");5 break;6 case 2:7 System.out.println("Tuesday");8 break;9 default:10 System.out.println("Other");11}Expression Form Arrow Syntax (Java 14+)
1int a = 2;2String day = switch (a) {3 case 1 -> "Monday";4 case 2 -> "Tuesday";5 default -> "Other";6};7System.out.println(day); // TuesdayBoth of these work exactly the same in Java 21. Pattern matching adds object support on top of this foundation.
4. Pattern Matching for Switch Core Syntax
Syntax
1switch (objectVariable) {2 case TypeName patternVariable -> {3 // use patternVariable here4 }5 case AnotherType anotherVar -> {6 // use anotherVar here7 }8 default -> {9 // handle anything else10 }11}Or as an expression:
1String result = switch (objectVariable) {2 case TypeName patternVariable -> "matched TypeName";3 case AnotherType anotherVar -> "matched AnotherType";4 default -> "no match";5};Syntax Breakdown
| Part | Meaning |
|---|---|
switch (objectVariable) | The variable being tested — can now be any Object |
case TypeName patternVariable | Match if objectVariable instanceof TypeName; bind to patternVariable |
-> | Arrow form (Java 14+); no break needed |
default | Handles all non-matched cases |
Beginner Code Example
1public class PatternSwitchBasic {2 public static void main(String[] args) {3 Object obj = "Hello World";4 describe(obj);5
6 obj = 42;7 describe(obj);8
9 obj = 3.14;10 describe(obj);11 }12
13 static void describe(Object obj) {14 switch (obj) {15 case String s -> System.out.println("String of length " + s.length());16 case Integer i -> System.out.println("Integer, doubled: " + (i * 2));17 case Double d -> System.out.println("Double, rounded: " + Math.round(d));18 default -> System.out.println("Unknown type: " + obj);19 }20 }21}String of length 11 Integer, doubled: 84 Double, rounded: 3
Line-by-Line Explanation
| Line | Explanation |
|---|---|
switch (obj) | obj is of type Object — now legal in Java 21 |
case String s -> | Check: is obj instanceof String? If yes, bind to variable s |
s.length() | s is already a String — no casting needed |
case Integer i -> | Check: is obj instanceof Integer? If yes, bind to i |
case Double d -> | Check: is obj instanceof Double? If yes, bind to d |
default -> | Runs if no case matched |
Intermediate Example As an Expression
1static String format(Object obj) {2 return switch (obj) {3 case Integer i -> "int: " + i;4 case Long l -> "long: " + l;5 case String s -> "str: " + s.toUpperCase();6 case null -> "null value";7 default -> "other: " + obj.getClass().getSimpleName();8 };9}10
11public static void main(String[] args) {12 System.out.println(format(100)); // int: 10013 System.out.println(format(100L)); // long: 10014 System.out.println(format("hello")); // str: HELLO15 System.out.println(format(null)); // null value16 System.out.println(format(3.14)); // other: Double17}5. Internal Working How It Really Works
What the Compiler Actually Generates
When you write:
1switch (obj) {2 case String s -> System.out.println("String: " + s);3 case Integer i -> System.out.println("Integer: " + i);4 default -> System.out.println("Other");5}The Java compiler translates this into the equivalent of:
1if (obj instanceof String s) {2 System.out.println("String: " + s);3} else if (obj instanceof Integer i) {4 System.out.println("Integer: " + i);5} else {6 System.out.println("Other");7}The pattern switch is syntactic sugar over instanceof chains. The JVM executes them identically.
Execution Flow
Step-by-Step Execution
- The switch selector expression (
obj) is evaluated once - Java checks each case in order from top to bottom
- For each
case TypeName varName:
- Java internally runs
obj instanceof TypeName - If
true: the object is cast toTypeName, bound tovarName, and the case body executes - If
false: move to the next case
- If no case matches:
defaultexecutes - The pattern variable (
varName) is only in scope within its case block
6. Performance: Pattern Switch vs Classic Switch vs if-else
This is a critical distinction that frequently appears in interviews.
Classic Switch with Primitives Jump Table / Lookup Table
When you use a classic switch with integer-like primitives (int, byte, short, char), the JVM compiles it to one of two bytecode instructions:
| Bytecode instruction | Used when | Behavior |
|---|---|---|
tableswitch | Cases are dense/contiguous (e.g., 1, 2, 3, 4) | O(1) — direct jump via index |
lookupswitch | Cases are sparse (e.g., 1, 100, 1000) | O(log n) — binary search |
Both are faster than if-else chains because they do not evaluate conditions one by one.
Pattern Switch with Objects Sequential `instanceof` Checks
When you use pattern switch with object types:
- The compiler generates sequential
instanceofchecks (essentiallyif-else ifchains) - Performance is O(n) — proportional to the number of cases
- There is no jump table or lookup table for object types
Performance Comparison Table
| Scenario | Implementation | Performance |
|---|---|---|
switch on int / String / enum | Jump table or lookup table | O(1) or O(log n) — fastest |
Pattern switch on objects | Sequential instanceof checks | O(n) — same as if-else |
Plain if-else if on objects | Sequential instanceof checks | O(n) |
if-else if chain. The benefit is purely readability and expressiveness. Only the classic switch on primitives/enums/strings benefits from jump/lookup table optimization.7. Scope of Pattern Variables
Rule
A pattern variable declared in a case block is only accessible within that specific case block. It is not visible in:
- Other case blocks
- The
defaultblock - Code after the
switchstatement
Code Example
1Object obj = "Hello";2
3switch (obj) {4 case String s -> {5 System.out.println(s.toUpperCase()); // ✅ s is visible here6 }7 case Integer i -> {8 // System.out.println(s); // ❌ Compile error: s not visible here9 System.out.println(i * 2);10 }11 default -> {12 // System.out.println(s); // ❌ Compile error: s not visible here13 System.out.println("Unknown");14 }15}16// System.out.println(s); // ❌ Compile error: s not visible outside switchDiagram
8. Pattern Matching with Inheritance
Overview
Pattern switch can handle class hierarchies intelligently. You can use parent types, child types, sibling types, and abstract types as case labels — as long as the object being switched on could possibly be an instance of that type.
Example Hierarchy
1abstract class Vehicle {2 abstract void drive();3}4
5class TwoWheeler extends Vehicle {6 @Override public void drive() { System.out.println("Two wheels!"); }7}8
9class Bike extends TwoWheeler {10 @Override public void drive() { System.out.println("Riding bike!"); }11}12
13class Cycle extends TwoWheeler {14 @Override public void drive() { System.out.println("Cycling!"); }15}16
17class FourWheeler extends Vehicle {18 @Override public void drive() { System.out.println("Four wheels!"); }19}Valid Cases When Switching on a `TwoWheeler` Object
1static void validate(TwoWheeler twoObj) {2 switch (twoObj) {3 case Bike b -> System.out.println("It's a Bike");4 case Cycle c -> System.out.println("It's a Cycle");5 case TwoWheeler t -> System.out.println("It's a TwoWheeler (not Bike or Cycle)");6 // case Vehicle v -> // ❌ Error: duplicate unconditional pattern7 // case FourWheeler f -> // ❌ Error: FourWheeler can never be a TwoWheeler8 }9}The "Unconditional Pattern" Conflict
Both Vehicle v and TwoWheeler t are unconditional patterns when the switch selector is a TwoWheeler — meaning both can match every possible TwoWheeler (itself, Bike, and Cycle).
Having two unconditional patterns is a compile error: Duplicate unconditional pattern.
Rule: You can include at most one type that can catch all remaining cases (either the type itself or a parent type). Mixing two such types is ambiguous and disallowed.
Case Validity Rules
| Case type | Valid when switching on TwoWheeler? | Why |
|---|---|---|
Bike | ✅ Yes | Bike extends TwoWheeler |
Cycle | ✅ Yes | Cycle extends TwoWheeler |
TwoWheeler | ✅ Yes (one unconditional allowed) | The type itself |
Vehicle | ✅ Yes (but conflicts with TwoWheeler) | Parent — catches all |
FourWheeler | ❌ No | Can never be an instance of TwoWheeler |
TwoWheeler + Vehicle together | ❌ No | Duplicate unconditional patterns |
Duplicate unconditional pattern.9. Pattern Matching with Enums
Overview
Pattern matching with enums allows you to match an object against an enum type using the instanceof mechanism, and then access the matched enum value through the pattern variable.
Without Pattern Matching (Traditional Enum Switch)
1enum Color { RED, GREEN, BLUE, YELLOW }2
3Color color = Color.RED;4
5switch (color) {6 case RED -> System.out.println("Red");7 case GREEN -> System.out.println("Green");8 case BLUE -> System.out.println("Blue");9 default -> System.out.println("Other");10}This is clean for simple cases. But if color is declared as Object:
1Object obj = Color.RED;2// You cannot use: switch (obj) { case RED -> ... }3// Because obj is Object, not ColorWith Pattern Matching Enum Switch on `Object`
1Object obj = Color.GREEN;2
3switch (obj) {4 case Color c -> System.out.println("Color name: " + c.name());5 default -> System.out.println("Not a Color");6}Object obj = Color.RED;
switch (obj) {
case Color c when c == Color.RED -> System.out.println("It's RED");
case Color c when c == Color.GREEN -> System.out.println("It's GREEN");
case Color c -> System.out.println("Other color: " + c.name());
default -> System.out.println("Not a Color");
}(The when clause is explained in detail in section 12.)
10. Null Handling in Pattern Switch
The Problem with `null` in Classic Switch
In a traditional switch, passing null as the selector throws a NullPointerException immediately, before any case is evaluated:
1String s = null;2switch (s) { // ❌ Throws NullPointerException at runtime3 case "hello" -> System.out.println("hi");4 default -> System.out.println("other");5}Pattern Switch is Null-Safe (for Pattern Cases)
In a pattern switch, when the selector is null:
- Pattern cases like
case String swill not match (becausenull instanceof Stringisfalse) - No
NullPointerExceptionis thrown during theinstanceofcheck - Execution falls through to the
defaultblock
1Object obj = null;2
3switch (obj) {4 case String s -> System.out.println("String: " + s); // instanceof = false, skipped5 case Integer i -> System.out.println("Integer: " + i); // instanceof = false, skipped6 default -> System.out.println("Reached default: obj is null or unknown");7}Object obj = null;
switch (obj) {
case null -> System.out.println("Value is null");
case String s -> System.out.println("String: " + s);
default -> System.out.println("Other");
}Output: Value is null
Null Safety Rule Summary
| Scenario | Result |
|---|---|
null in classic switch | NullPointerException |
null in pattern switch, no case null | Falls to default — no NPE |
null in pattern switch, with case null | Matches case null |
null instanceof AnyType | Always false — never matches a type pattern |
case null or handle default carefully when you expect the switch selector might be null. Pattern switch will not throw NPE from a type pattern failing, but it also won't tell you it was null unless you explicitly handle it.11. Grouping of Patterns What Is NOT Allowed
Background Grouping in Classic Switch
In traditional switch, you can group multiple constants under one action:
1switch (day) {2 case 1, 7 -> System.out.println("Weekend"); // grouping allowed3 default -> System.out.println("Weekday");4}Pattern Variables CANNOT Be Grouped
You cannot group multiple type patterns that each declare a pattern variable:
1// ❌ Compile error2switch (obj) {3 case Circle c, Square s -> System.out.println("Shape"); // NOT allowed4}Error: Multiple switch labels are permitted for a switch label statement group only if none of them declare any pattern variable.
Why Grouping Is Impossible
If both Circle c and Square s were grouped:
- Which variable would be bound?
cors? - If the object is a
Circle,sis not initialized - If the object is a
Square,cis not initialized - The compiler cannot guarantee either variable is safe to use in the body
Each pattern case must stand alone, guaranteeing exactly one variable is bound and safe.
What IS Allowed Grouping Without Pattern Variables
1// ✅ Allowed — no pattern variables declared2switch (obj) {3 case Circle, Square -> System.out.println("It's a shape (no variable)");4 default -> System.out.println("Other");5}This works because no variable binding is involved — just the type check.
Summary
| Case style | Allowed? | Reason |
|---|---|---|
case 1, 2 -> (primitive grouping) | ✅ | No variables involved |
case Circle, Square -> (type grouping, no variables) | ✅ | No variable binding conflict |
case Circle c, Square s -> (grouped patterns with variables) | ❌ | Ambiguous variable binding |
12. Guarded Patterns The `when` Clause
Overview
A guarded pattern allows you to add an extra boolean condition to a pattern case. After the type pattern matches (and the variable is bound), the when condition is evaluated. Both must be true for the case body to execute.
Why This Exists
Sometimes a type match alone isn't sufficient. You need to match the type AND check a condition on the matched value:
1// Without guarded pattern — messy nested if2switch (obj) {3 case String s -> {4 if (s.contains("H") || s.contains("h")) {5 System.out.println("Contains H: " + s);6 }7 // else: nothing — falls to next case? No — already in this case body8 }9}This is awkward. A guarded pattern makes it clean.
Syntax
1switch (selectorExpression) {2 case TypeName varName when booleanCondition -> {3 // Executes only if:4 // 1. obj instanceof TypeName (pattern matches)5 // 2. booleanCondition is true6 }7 default -> {8 // Executes if pattern didn't match OR when condition was false9 }10}Code Example
1Object obj = "Hello World";2
3switch (obj) {4 case String s when s.contains("H") || s.contains("h") ->5 System.out.println("String containing H: " + s);6
7 case String s ->8 System.out.println("String without H: " + s);9
10 default ->11 System.out.println("Not a string");12}static String classify(Object obj) {
return switch (obj) {
case Integer i when i < 0 -> "Negative integer: " + i;
case Integer i when i == 0 -> "Zero";
case Integer i when i > 0 -> "Positive integer: " + i;
case String s when s.isEmpty() -> "Empty string";
case String s when s.length() > 10 -> "Long string: " + s;
case String s -> "Short string: " + s;
case null -> "null";
default -> "Other type: " + obj.getClass().getSimpleName();
};
}
public static void main(String[] args) {
System.out.println(classify(-5)); // Negative integer: -5
System.out.println(classify(0)); // Zero
System.out.println(classify(42)); // Positive integer: 42
System.out.println(classify("")); // Empty string
System.out.println(classify("Hi")); // Short string: Hi
System.out.println(classify("Hello World!")); // Long string: Hello World!
System.out.println(classify(null)); // null
System.out.println(classify(3.14)); // Other type: Double
}Output:
1Negative integer: -52Zero3Positive integer: 424Empty string5Short string: Hi6Long string: Hello World!7null8Other type: DoubleExecution Flowchart for Guarded Pattern
13. Quick Reference Table
| Feature | Syntax | Notes | ||
|---|---|---|---|---|
| Basic type pattern | case String s -> | Matches if obj instanceof String; binds to s | ||
| Null case | case null -> | Explicit null handling | ||
| Default case | default -> | Catches everything else | ||
| Guarded pattern | case String s when s.length() > 5 -> | Pattern + extra condition | ||
| Inheritance — child type | case Bike b -> | Valid: child of selector's type | ||
| Inheritance — parent type | case Vehicle v -> | Valid: acts as catch-all | ||
| Grouped type patterns (no var) | case Circle, Square -> | Valid: no binding needed | ||
| Grouped type patterns (with var) | case Circle c, Square s -> | ❌ Compile error | ||
| Two unconditional patterns | case TwoWheeler t + case Vehicle v | ❌ Compile error | ||
| OR in when clause | `when a \ | \ | b` (as grouping) | ❌ Not for variable patterns |
| AND in when clause | when a && b | ✅ Allowed |
14. Interview Notes
Q1: What is Pattern Matching for Switch and when was it finalized?
Answer: It is a Java feature that extends switch to support object types (classes, interfaces, abstract types) as case labels. Each case can declare a pattern variable that is automatically type-cast when matched. It was introduced as a preview in Java 17 and finalized in Java 21.
Q2: What types does a classic switch support that pattern switch also supports?
Answer: Classic switch supports int, byte, short, char, their wrapper types, String, and enum. Pattern switch supports all of these plus any class, interface, abstract class, or Object.
Q3: Is Pattern Matching for Switch faster than `if-else if`?
Answer: No — not when working with object types. Internally, the compiler generates sequential instanceof checks, which is functionally identical to an if-else if chain. Performance is O(n). The benefit is purely readability and structure. Classic switch on primitives and strings remains faster because it uses jump tables or lookup tables.
Q4: What is the scope of a pattern variable in a switch case?
Answer: The pattern variable is only visible inside the case block it is declared in. It cannot be accessed in other case blocks, the default block, or outside the switch statement.
Q5: What is a "duplicate unconditional pattern" error?
Answer: This occurs when two cases in a pattern switch can both match every possible value of the selector type. For example, switching on a TwoWheeler and having both case TwoWheeler t and case Vehicle v — since Vehicle is the parent, both can catch any TwoWheeler. The compiler rejects this ambiguity.
Q6: Why can't you group pattern cases that declare variables?
Answer: Because it would create ambiguity about which variable is bound. For case Circle c, Square s, if the object is a Circle, then s is uninitialized and unsafe to use. The compiler cannot guarantee both are bound, so grouping pattern variables is forbidden.
Q7: What is a guarded pattern and what keyword does it use?
Answer: A guarded pattern adds an extra boolean condition to a type pattern using the when keyword. Both the type pattern (the instanceof check) and the when condition must be true for the case to execute. when is equivalent to && in instanceof pattern matching — OR conditions are not allowed.
Q8: How does pattern switch handle `null`?
Answer: Type patterns are null-safe — null instanceof AnyType is always false, so a null selector will not match any type pattern and will not throw a NullPointerException. It falls through to default (or a case null if you add one explicitly). Classic switch throws NullPointerException immediately for null selectors.
Q9: What is the relationship between Pattern Matching for Switch and `instanceof` pattern matching?
Answer: They use the same underlying mechanism. Each case TypeName varName in a pattern switch is equivalent to obj instanceof TypeName varName. The switch form is more readable for multiple type checks and adds exhaustiveness checking, but internally the compiler generates instanceof chains.
Q10: Can you use `yield` in a pattern switch expression?
Answer: Yes. Pattern switch supports all Java 14+ switch expression features including yield. Inside a block-style case (case Type t -> { ... }), use yield value; to return a value from the switch expression.
1String result = switch (obj) {2 case String s -> {3 String upper = s.toUpperCase();4 yield "String: " + upper; // yield returns from block5 }6 default -> "other";7};15. Common Mistakes
1// Assumption: switch is always faster than if-else2// ❌ Wrong for object types3switch (obj) {4 case String s -> process(s);5 case Integer i -> process(i);6}7
8// ✅ Reality: for object types, this is equivalent in performance to:9if (obj instanceof String s) {10 process(s);11} else if (obj instanceof Integer i) {12 process(i);13}14// Use pattern switch for readability, not speed1switch (obj) {2 case String s -> System.out.println(s);3 default -> System.out.println(s); // ❌ Compile error: 's' not in scope4}1// Switching on TwoWheeler2switch (twoWheeler) {3 case Bike b -> System.out.println("Bike");4 case TwoWheeler t -> System.out.println("TwoWheeler"); // unconditional5 case Vehicle v -> System.out.println("Vehicle"); // ❌ also unconditional: Duplicate!6}1// ❌ Compile error2switch (obj) {3 case Circle c, Square s -> System.out.println("Shape");4}5
6// ✅ Correct — separate cases7switch (obj) {8 case Circle c -> System.out.println("Circle: r=" + c.radius());9 case Square s -> System.out.println("Square: side=" + s.side());10}1Object obj = null;2switch (obj) {3 case String s -> System.out.println(s); // ❌ Won't execute — null is not instanceof String4 default -> System.out.println("default"); // ✅ This runs5}6// Always add case null -> if you need to handle null explicitlywhen with OR logic1// Trying to write OR with when — NOT possible for pattern variables2// ❌ Wrong assumption:3case String s when s.contains("a") || s.contains("b")4// This 'when' line itself is valid! OR inside 'when' is allowed.5// What is NOT allowed is grouping TWO pattern cases with OR:6// case String s || Integer i ← this does not existwhen clause (when x || y) is actually valid Java — you're writing a regular boolean expression. What is NOT allowed is using OR to combine two different pattern variables as case labels. The lecture's key point is that you cannot do case Circle c, Square s (two patterns with variables joined), not that you cannot use || inside when.16. Best Practices
- Always include a
defaultcase — even with sealed classes, adefaultguards against future subtypes added to non-sealed branches.
- Order cases from most specific to most general — put child types before parent types. If a parent type comes first, child-specific cases become unreachable.
- Use
case nullexplicitly when the selector might be null — don't silently let nulls fall todefaultif null deserves special handling.
- Use guarded patterns (
when) to avoid nestedifinside case bodies — it's cleaner and signals intent clearly.
- Don't use pattern switch expecting a performance win — the gain over
if-else ifis zero for object types. Use it for readability only.
- Use pattern switch with sealed classes — sealed class hierarchies give the compiler exhaustiveness information, making your switch provably complete without a
default.
- Keep case bodies short — if a case body grows large, extract it into a method and call it from the case.
- Don't use two unconditional patterns — if you need a catch-all for a type hierarchy, use exactly one (either the type itself or a parent, not both).
17. Practice Questions
Easy
- What Java version finalized Pattern Matching for Switch?
- What types does classic switch support that pattern switch also adds to?
- Is a pattern variable accessible in the
defaultblock? Why or why not? - What keyword is used to add an extra condition to a pattern case?
- What happens when a
nullvalue is passed to a pattern switch that has nocase null?
Medium
- Write a
describe(Object obj)method using pattern switch that handlesInteger,Double,String,Boolean, and a default case. - Given a hierarchy
Shape → Circle, Square, Triangle, write a pattern switch on aShapeobject. What types can be valid cases? What would cause a "duplicate unconditional pattern" error? - Rewrite this
if-else ifchain using pattern switch:
1 if (obj instanceof Integer i && i > 100) { ... }2 else if (obj instanceof Integer i) { ... }3 else if (obj instanceof String s && !s.isEmpty()) { ... }4 else { ... }- Why can't you group
case Circle c, Square sbut can groupcase Circle, Square? - Explain why switching on an object type is O(n) while switching on an int is O(1).
Hard
- You have a sealed interface
Resultwith permitted implementationsSuccess(String message),Failure(String error),Pending. Write a complete pattern switch that handles all three, including aSuccesswith a message longer than 50 characters handled differently from shorter ones. - Compare the bytecode behavior of
switch(intVal)vsswitch(objectVal). What bytecode instructions are used and why? - Explain why OR grouping of pattern cases with variables is a compile error, but AND conditions inside
whenare allowed. What is the fundamental reason? - Design a type-safe event dispatcher using pattern switch. The event hierarchy has
UserEvent(subclasses:LoginEvent,LogoutEvent) andSystemEvent(subclasses:StartupEvent,ShutdownEvent). Show how to route each event type. - What would happen in a pattern switch if you put a parent type case before a child type case? Demonstrate with an example.
18. Summary
Quick Revision Bullets
- Pattern Matching for Switch finalised in Java 21; allows classes, interfaces, and abstract types as case labels
- Internally translates to
instanceofchains — same mechanism as Java 16instanceofpattern matching - Pattern variable scope is limited to its own case block only; not accessible in other cases,
default, or after the switch - Performance for object types is O(n) — same as
if-else if; no jump/lookup table; classic switch on primitives remains faster - Null: type patterns are null-safe (won't NPE);
nullfalls todefaultunlesscase nullis added explicitly - Inheritance: use child types, the exact type, or ONE parent type — never two unconditional patterns simultaneously
- Grouping: pattern cases with variables CANNOT be grouped (
case Circle c, Square sis illegal); cases without variables can be grouped - Guarded patterns: use
when booleanExprto add extra AND conditions after a type pattern matches - Supports all Java 14+ switch features: arrow syntax,
yield, expression form - Use pattern switch for readability, not performance — for object types it offers no speed advantage over
if-else if
This guide covers Pattern Matching for Switch as finalised in Java 21. For the complete JEP specification, see JEP 441.
Mastery check
How well can you recall this?
Finished this lesson?