Command Palette

Search for a command to run...

Back to the lesson: Topic 11.3 — Record Patterns
Core Java · Example 3 of 3 Java 21+

Generic records, inference and nested exhaustiveness

A record pattern like Point(int x, int y) checks that a value is a Point and pulls out its components into variables in one step. Record patterns nest, so Line(Point(var x1, var y1), Point p2) matches and unpacks a whole tree of records at once, in instanceof and in switch.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

With record Point(int x, int y) and record Line(Point from, Point to), write kind(Line) returning "a single point", "horizontal", "vertical", "diagonal" (45 degrees) or "sloped", using nested record patterns and guards.

02

Model a binary tree as sealed interface Tree permits Leaf, Node with record Leaf() and record Node(Tree left, int value, Tree right). Write sum, height and isLeafNode (a node whose children are both leaves) with record patterns.

03

Model a café bill: sealed interface Item permits Food, Drink, Food(String name, int pricePaise), Drink(String name, int pricePaise, boolean large), and Line(Item item, int qty). Large drinks cost 1000 paise more; 3 or more of the same food get 10% off. Write total(Line) with nested patterns and print a bill.

Explain it without notes

01

What does o instanceof Point(int x, int y) do, step by step?

02

How do record patterns behave with null, both for the record and for its components?

03

How does the compiler check exhaustiveness for nested record patterns over sealed types?

04

Why can't you write a record pattern for an ordinary class?

05

What is the relationship between records, sealed interfaces and record patterns?

Generic records, inference and nested exhaustiveness Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

Expected output

Asha & Ravi
Asha alone
Ravi alone
nobody
Pair[first=2, second=left]