Pattern Matching
Java’s boilerplate doesn’t just live in classes; it also lives inside our logic. Traditionally, checking a type and then using it required casting. Modern Java fixes this with Pattern Matching.
1. Pattern Matching for instanceof
Before, you had to check the type and then manually cast the variable. Now, you do it in one go.
// LEGACY
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
// MODERN (Java 16+)
if (obj instanceof String s) {
System.out.println(s.length());
}
2. Switch Expressions
The switch statement has been revamped into a high-performance expression that returns a value.
int days = switch (month) {
case JAN, MAR, MAY -> 31;
case APR, JUN -> 30;
case FEB -> {
yield 28; // Use yield for multi-line logic
}
};
3. Pattern Matching for switch (Java 21)
This is the “Superpower” of modern Java. You can switch on Types and even check conditions (Guards).
String description = switch (obj) {
case Integer i -> "An integer: " + i;
case String s && s.length() > 5 -> "A long string";
case String s -> "A short string";
case null -> "It's null!";
default -> "Unknown type";
};
4. Interactive: Pattern Matcher
See the compiler handle different types.
Input Type: Object
➡️
switch(obj) {
case String s && s.len > 5
case String s
case Integer i
case null
}
5. Record Patterns (Java 21)
You can even deconstruct Records directly in a pattern.
if (obj instanceof User(String name, String email)) {
System.out.println("User is " + name); // No need for user.name()
}
This makes working with nested data incredibly clean and expressive.