Nearby lessons

103 of 125

Java - 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
JCode Cell
1// OLD - check, cast, use
2if (obj instanceof String) {
3 String s = (String) obj; // cast needed
4 System.out.println(s.length());
5}
6 
7// NEW - pattern matching (previewed in 14, final in 16)
8if (obj instanceof String s) { // s is created directly
9 System.out.println(s.length());
10}

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
JCode Cell
1record Point(int x, int y) { }
2 
3String describe(Object obj) {
4 return switch (obj) {
5 case null -> "It is null";
6 case String s -> "A String: " + s;
7 case Point p -> "A point at " + p.x() + "," + p.y();
8 case Integer i -> "A number: " + i;
9 default -> "Something else";
10 };
11}
📝 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 Questions
Progress: 0 / 2