Pattern Matching in switch (Preview/Java 17+)
You'll learn how to use type patterns in switch to branch on an object's actual type, not just its value.
What Are Type Patterns in Switch?
Until now, you've used switch to test values—checking if an integer equals 1, 2, 3, or if a String matches specific text. Type pattern matching extends switch to test what type an object is, similar to how you'd use multiple instanceof checks.
Think of it like a sorting machine at a recycling center: instead of checking "Is this item red or blue?" (value-based), you're checking "Is this item plastic, glass, or metal?" (type-based).
How It Works
With pattern matching, you can write a switch that accepts a general type (like Object) and branches based on the runtime type:
Object obj = "Hello";
String result = switch (obj) {
case Integer i -> "It's an integer: " + i;
case String s -> "It's a string: " + s;
case Double d -> "It's a double: " + d;
default -> "Unknown type";
};
// result is "It's a string: Hello"
Notice case Integer i introduces a pattern variable i that you can use immediately in the arrow expression. The switch automatically casts and binds the value for you.
Why This Matters
Before type patterns, you'd write a chain of if-else statements with instanceof. Type pattern matching makes your code cleaner and more expressive when dealing with different types.
Key Takeaway: Pattern matching in switch lets you branch on object types, not just values, automatically casting and binding the object to a pattern variable for immediate use.