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
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.
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.