Writing clean and readable code is super important — especially in large projects. Java 21 introduces powerful improvements in Pattern Matching in Java 21 that help you write less code while doing more.
In this post, you’ll learn:
✅ What pattern matching is
✅ How to use it with instanceof
✅ How it works in switch
statements
✅ Why it’s useful in real-world coding
Let’s dive in!

🧩 What is Pattern Matching in Java 21?
Pattern Matching lets Java check the type of an object and extract it in a cleaner way.
Before Java 16, if you used instanceof
, you had to write extra code to cast the object.
Old Way
1 2 3 4 5 6 7 8 9 10 |
Object obj = "Hello"; if (obj instanceof String) { String str = (String) obj; // extra cast System.out.println(str.toLowerCase()); } |
New Way in Java 21
1 2 3 4 5 6 7 8 9 |
Object obj = "Hello"; if (obj instanceof String str) { System.out.println(str.toLowerCase()); // no cast needed } |
Much cleaner, right?
You check and use the object in one step!
🔄 Pattern Matching in Java 21 with switch
Java 21 now allows type patterns in switch
statements too.
This makes it easy to handle multiple object types in one place.
1 2 3 4 5 6 7 8 9 10 11 12 |
static String handleShape(Object shape) { return switch (shape) { case String s -> "A string of length " + s.length(); case Integer i -> "An integer: " + i; case null -> "It’s null!"; default -> "Unknown type"; }; } |
No more long if-else
blocks — just clean and readable code.
🔒 Guarded Patterns
You can also add conditions (guards) inside switch cases.
1 2 3 4 5 6 7 8 9 10 11 12 |
static String describeNumber(Number n) { return switch (n) { case Integer i when i > 0 -> "Positive Integer"; case Integer i -> "Non-positive Integer"; case Double d -> "A double: " + d; default -> "Unknown number"; }; } |
🧪 Real-World Example
Let’s say you’re handling user input:
1 2 3 4 5 6 7 8 9 10 11 |
public void processInput(Object input) { switch (input) { case String s -> System.out.println("User typed: " + s); case Integer i -> System.out.println("User entered number: " + i); case Boolean b -> System.out.println("A true/false value: " + b); default -> System.out.println("Unknown input"); } } |
This is much easier than writing if-else
for every type.
📌 Benefits of Pattern Matching
- ✅ Less boilerplate code
- ✅ Safer (no casting errors)
- ✅ Cleaner and more readable logic
- ✅ Great for working with objects, especially in APIs or UI input
🧾 Summary
Feature | Description |
---|---|
instanceof Pattern | Check type and assign in one line |
switch Pattern | Handle multiple types in one switch |
Guarded Patterns | Add conditions inside switch cases |
Java Version | Fully available in Java 21 |
💡 Final Thoughts
Java 21 continues to make Java easier and more fun to write.
Pattern Matching helps you avoid clumsy code and focus on what really matters — your logic.
If you’re a beginner, this is one of the most useful features to learn early!
Reference : Pattern Matching