Introduction
Before pattern matching, developers had to check an object’s type using the instanceof operator and then explicitly cast it before accessing its methods or properties. This resulted in repetitive boilerplate code. Pattern Matching removes this redundancy, making Java code cleaner and easier to maintain.
Pattern Matching was first introduced as a preview feature in Java 14, enhanced in Java 16, officially finalized in Java 16 for instanceof, and later expanded for switch expressions in Java 17–21.
What is Java Pattern Matching?
Pattern Matching is a Java feature that allows you to test whether an object matches a particular type and automatically declare a variable of that type if the match succeeds.
Instead of writing:
if (obj instanceof String) {
String str = (String) obj;
System.out.println(str.length());
}
You can simply write:
if (obj instanceof String str) {
System.out.println(str.length());
}
Here,
- Java checks whether obj is a String.
- If true, it automatically creates the variable str.
- No explicit type casting is required.
This makes the code shorter, safer, and more readable.
Why Use Pattern Matching?
Pattern Matching offers several advantages:
- Eliminates unnecessary type casting
- Reduces boilerplate code
- Improves readability
- Makes code less error-prone
- Simplifies object processing
- Works seamlessly with Records and Sealed Classes
- Makes switch statements more powerful
Syntax
Pattern Matching with instanceof
if (object instanceof Type variableName) {
// use variableName directly
}
Example
Object value = "Java Tutorial";
if (value instanceof String text) {
System.out.println(text.toUpperCase());
}
Output
Without Pattern Matching
Traditional Java code:
Object obj = "Programming";
if (obj instanceof String) {
String str = (String) obj;
System.out.println(str.length());
}
With Pattern Matching
Modern Java:
Object obj = "Programming";
if (obj instanceof String str) {
System.out.println(str.length());
}
Notice how the explicit cast disappears.
How Pattern Matching Works
Suppose we have:
Object obj = "Hello";
Java performs these steps:
- Checks whether obj is a String.
- If yes, creates a new variable named str.
- str is automatically cast to String.
- The variable exists only inside the matching scope.
Example 1: Checking String
public class Main {
public static void main(String[] args) {
Object obj = "Welcome"
if (obj instanceof String str) {
System.out.println("Length: " + str.length());
}
}
}
Output
Example 2: Checking Integer
public class Main {
public static void main(String[] args) {
Object value = 100;
if (value instanceof Integer number) {
System.out.println(number * 2);
}
}
}
Output
Example 3: Using Else Block
Object obj = 25;
if (obj instanceof String text) {
System.out.println(text);
} else {
System.out.println("Not a String");
}
Output
Pattern Matching with Logical Operators
You can combine Pattern Matching with additional conditions.
Object obj = "Java";
if (obj instanceof String str && str.length() > 3) {
System.out.println(str);
}
Output
Here,
- Java first checks the type.
- Then evaluates the second condition.
Pattern Matching in switch
Java 21 significantly enhanced Pattern Matching by supporting it inside switch.
Example:
public class Main {
public static void main(String[] args) {
Object obj = 45;
String result = switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s
case Double d -> "Double: " + d;
default -> "Unknown";
};
System.out.println(result);
}
}
Output
This is much cleaner than writing multiple instanceof checks.
Example with Multiple Types
Object data = 10.5;
switch (data) {
case Integer i ->
System.out.println("Integer");
case Double d ->
System.out.println("Double");
case String s ->
System.out.println("String");
default ->
System.out.println("Other");
}
Output
Pattern Matching with Records
Pattern Matching works particularly well with Records.
Example:
record Student(String name, int age) {}
public class Main {
public static void main(String[] args) {
Object obj = new Student("Rahul", 20);
if (obj instanceof Student student) {
System.out.println(student.name());
System.out.println(student.age());
}
}
}
Output
20
Pattern Matching with Sealed Classes
Suppose we have:
sealed interface Shape permits Circle, Rectangle {}
final class Circle implements Shape {
final class Rectangle implements Shape {}
Now,
Shape shape = new Circle();
switch (shape) {
case Circle c ->
System.out.println("Circle");
case Rectangle r ->
System.out.println("Rectangle");
}
No default case is required because Java knows all permitted subclasses.
Scope of Pattern Variables
The pattern variable exists only where the match is guaranteed.
Valid:
if (obj instanceof String str) {
System.out.println(str);
}
Invalid:
if (obj instanceof String str) {
}
System.out.println(str);
This causes a compilation error because str is outside its scope.
Benefits of Pattern Matching
1. Less Boilerplate
No manual casting.
2. Better Readability
The code becomes easier to understand.
3. Safer Code
Avoids accidental ClassCastException.
4. Modern Coding Style
Recommended for Java 17+ applications.
5. Better Integration
Works well with:
- Records
- Sealed Classes
- Switch Expressions
Real-Life Example
Imagine an online payment system.
Different payment methods:
class CreditCard {}
class UPI {}
class PayPal {}
Processing payments:
Object payment = new UPI();
if (payment instanceof UPI upi) {
System.out.println("Processing UPI payment");
}
else if (payment instanceof CreditCard card) {
System.out.println("Processing Credit Card payment");
}
else if (payment instanceof PayPal paypal) {
System.out.println("Processing PayPal payment");
}
Pattern Matching makes handling multiple object types much cleaner.
Traditional Approach vs Pattern Matching
| Traditional Java | Pattern Matching |
|---|---|
| Uses instanceof + cast | Uses single statement |
| More code | Less code |
| Manual casting | Automatic casting |
| More boilerplate | Cleaner syntax |
| Harder to read | Easier to read |
| Higher chance of mistakes | Safer |
Best Practices
- Use Pattern Matching whenever you perform instanceof checks.
- Prefer switch Pattern Matching for multiple object types.
- Keep pattern variables meaningful.
- Combine with Records and Sealed Classes.
- Avoid unnecessary nested conditions.
- Write exhaustive switch statements whenever possible.
Common Mistakes
1. Using Variable Outside Scope
Wrong
if (obj instanceof String str) {
}
System.out.println(str);
Correct
if (obj instanceof String str) {
System.out.println(str);
}
2. Unnecessary Casting
Wrong
if (obj instanceof String str) {
String s = (String) obj;
}
The cast is already done automatically.
3. Forgetting Null Handling
Object obj = null;
if (obj instanceof String str) {
System.out.println(str);
}
Nothing executes because null never matches a type pattern.
4. Overusing Nested if Statements
Instead of many nested checks, prefer Pattern Matching with switch.
Conclusion
Java Pattern Matching is one of the most valuable language enhancements introduced in recent Java versions. By combining type checking and casting into a single, concise operation, it significantly reduces boilerplate code and improves readability. When paired with features such as Records, Sealed Classes, and Pattern Matching for switch, it enables developers to write cleaner, safer, and more maintainable code.
If you’re developing applications with Java 17, Java 21, or later, adopting Pattern Matching is highly recommended.