Command Palette

Search for a command to run...

Back to the lesson: Topic 4.9 — Records
Core Java · Example 4 of 4 Java 21+

Record patterns in instanceof and switch

A record is a short way to declare a class that is just a carrier for immutable data. From one line, record Point(int x, int y) {}, Java generates private final fields, a constructor, accessor methods, and correct equals, hashCode and toString.

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

Declare record Rgb(int r, int g, int b) that rejects values outside 0..255 and has a method hex() returning #RRGGBB in upper case. Print new Rgb(255, 165, 0).hex() and a rejected colour.

02

Use a local record inside main to find the longest word in {"tea", "samosa", "chai"} together with its length, and print the record.

03

Declare record Student(String name, int marks) and use a TreeMap<String, Student> keyed by name to store three students, then print the map.

Explain it without notes

01

What exactly does the compiler generate for record Point(int x, int y) {}?

02

What is a compact constructor, and what can and can't you do in it?

03

Why can't a record declare additional instance fields or extend another class?

04

Explain shallow immutability in records and the array-component pitfall.

05

When would you choose a record, and when a normal class?

Record patterns in instanceof and switch 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

point on the diagonal at 2
point 1,5
vertical line at x=3
line from Point[x=0, y=0] to Point[x=4, y=4]
unknown: hello
sum of components: 15