Modern Java Features
Pattern Matching
Learn pattern matching for instanceof and switch blocks introduced in Java 17-21.
Interview: Focuses on smart casting scopes, pattern variables, and guarding switch conditions with 'when'.
Pattern Matching upgrades Java type checking. It combines instance validation checks and conditional type casting into a single step, removing boilerplate cast code.
Core Idea
Pattern matching performs type checks and binds the cast value to a scoped variable automatically.
Why It Matters
Removes repetitive casting patterns (e.g. String s = (String) obj;), improving code readability and safety.
Interview Lens
Tests scoping rules of pattern variables inside conditional logical branches.
Smart Casting and Scoping
When using pattern matching:
if (obj instanceof String s) {
System.out.println(s.toLowerCase()); // "s" is in scope here
}
// System.out.println(s); // ILLEGAL: s is out of scope here
The variable s is only in scope where the compiler can guarantee the type check succeeded.
Pattern Matching in Switch (Java 21)
Java 21 expands this to switch expressions, allowing you to match types and apply conditional guards using the when keyword:
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s when s.length() > 5 -> "Long String: " + s;
case String s -> "Short String: " + s;
default -> "Unknown";
};
Interview-Relevant Information
Q: How do scoping rules handle the OR operator (||) in pattern matching?
Answer: You cannot use the pattern variable after an OR (||) operator (e.g. if (obj instanceof String s || s.isEmpty()) is a compile error). Because if the left side fails, the right side still evaluates, but s remains uninitialized. You are, however, allowed to use it after an AND (&&) operator.
Quick Checklist
Where is the pattern variable in scope? How do you write a guard condition in a case branch? If yes, you understand pattern matching.
Use Cases
Simplifying custom equals() implementations.
Processing complex polymorphic payload types in messaging event listeners.
Common Mistakes
Attempting to reference the pattern variable outside the scope where the type check is guaranteed to have succeeded.
Ordering case branches incorrectly (more general types must be placed after more specific types; otherwise, the compiler flags unreachable code).