Compact constructor: validate, normalise, copy
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.
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.
Use a local record inside main to find the longest word in {"tea", "samosa", "chai"} together with its length, and print the record.
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
What exactly does the compiler generate for record Point(int x, int y) {}?
What is a compact constructor, and what can and can't you do in it?
Why can't a record declare additional instance fields or extend another class?
Explain shallow immutability in records and the array-component pitfall.
When would you choose a record, and when a normal class?
Expected output
Range[lo=2, hi=5]
Range[lo=0, hi=7]
rejected: lo 5 > hi 2
Order[id=ORD-7, items=[tea, samosa]]
items() is unmodifiable