Nearby lessons
103 of 125Java - Pattern Matching
📌 What You Will Learn
- Switch expressions — now FINAL
- Records — the compact class (preview)
- Pattern matching for instanceof (preview)
- Helpful NullPointerException messages
- Text blocks second preview
Pattern Matching is a core concept of the Java language. This lesson explains Pattern Matching for instanceof (Preview) and Java 17+ — Pattern Matching for switch with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Pattern Matching for instanceof (Preview)
The classic instanceof pattern is awkward: check, then cast, then use. Pattern matching does it in one step:
The variable s is available inside the if block as a String — no separate cast. This became a permanent feature in Java 16.
In simple words: Pattern matching merges the type check and the cast into one step. When obj instanceof String s is true, the variable s is already a String inside the block — no separate cast is needed.
Example01
Java 17+ — Pattern Matching for switch
The switch can now match types, not just values. Combine with records and you get extremely clean code:
In simple words: A switch can now match the type of the value, not just its exact value. The variable after the type, like String s, is ready to use in that case — no cast required.
Example02
📝 Key Takeaways
- Switch expressions became FINAL in Java 14.
- Records create data classes with automatic constructor, getters, toString, equals, hashCode.
- Pattern matching for instanceof combines check and cast into one step.
- Helpful NPE messages tell you exactly which value was null.
- Text blocks got a second preview before becoming final in Java 15.
- After Java 14: Java 15-24 added text blocks, records, sealed classes, virtual threads.
🧠 Test Your Knowledge
2 QuestionsProgress: 0 / 2