AI Hints
Home›Java Tutorial›Optional, var and Pattern Matching
Java · Lesson 108 of 120

Pattern Matching

Test and unpack in one step.

⏱ 2 min read▶ Video at 2:17:47🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Often you check an object's type, and then cast it, to use it. Pattern matching does both in one step, with fewer chances for mistakes.

  • Check the type
  • Then cast it
  • Pattern matching does both

instanceof patterns

Instance of Circle c checks the type, and if it matches, gives us a variable c, already a circle. No cast is needed. A pattern can be combined with and, to add a condition. The order matters, so the big square check comes first. Run it. Each thing is described correctly. And forty two is something else.

Main.javajava
public class Main {
    record Circle(double r) {}   record Square(double side) {}
    static String describe(Object o) {
        if (o instanceof Circle c) {
            return String.format("circle, area %.1f", Math.PI * c.r() * c.r());
        } else if (o instanceof Square s && s.side() > 10) {
            return "a big square";
        } else if (o instanceof Square s) {
            return "square, area " + s.side() * s.side();
        } else if (o instanceof String text) {
            return "text with " + text.length() + " letters";
        }
        return "something else";
    }
    public static void main(String[] args) {
        Object[] things = { new Circle(2), new Square(3), new Square(12), "hello", 42 };
        for (Object t : things) System.out.println(describe(t));
    }
}
Output
circle, area 12.6
square, area 9.0
a big square
text with 5 letters
something else

What module twelve taught

Lambdas are small functions you can pass around. Functional interfaces give them a type. Method references point to existing methods. Streams process data, with filter, map, and collect. Optional handles missing values. And var, and pattern matching, keep code short.

keyvalue
Lambdasx -> x * 2
Streamsfilter, map, collect
OptionalorElse, map
Modernvar, instanceof patterns

Summary

Pattern matching checks a type, and gives you a typed variable, in one step. In Java twenty one and later, switch can do this too. That's the end of module twelve. Next module, useful tools, and our project.

Key takeaways
  • o instanceof Circle c
  • No cast
  • Add && conditions
Next up: StringBuilder — build text efficiently