Command Palette

Search for a command to run...

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

A record does the boilerplate for you

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?

A record does the boilerplate for you Java 16+
Sign in to run this example in your browser.

Expected output

Point[x=3, y=4]
x = 3, y = 4
a == b: false, a.equals(b): true
same hash: true
distance: 5.0
a still Point[x=3, y=4], c is Point[x=10, y=4]
set size: 1
lookup: origin