Records, Sealed, Immutable Classes. Practical Tasks
The Order class has all its fields private final, no setters, and is declared final, and yet an order still changes: someone added an item to the list they passed to the constructor. The first exercise below is built around this bug. It is hard to grasp from a description, but once you reproduce it and fix it yourself, you remember it for a long time.
This page collects Java exercises on records, sealed classes and immutable objects. There are three hands-on exercises, one for each lesson of the module: an immutable class with defensive copies, a record with a compact constructor and record patterns, and a sealed hierarchy with a switch that has no default. The exercises follow the order of the lessons, and each one builds on the previous one. Every exercise has a hint, and the task text gives the expected output and the compiler messages you should see.
What to review first
Each exercise practices one lesson. If you get stuck, go back to the lesson in the table.
| Topic | Lesson | Exercise on this page |
|---|---|---|
| The five rules of an immutable class, defensive copies, with-methods | Immutable classes in Java | Immutable Order class |
| Compact constructor, extra constructors, record patterns | Java records | Record Price |
permits, non-sealed, switch over a sealed type | Sealed classes and interfaces | Sealed payment hierarchy |
Immutable Order Class: Defensive Copies and with-Methods
- Create an
Orderclass with the fieldsString id,java.util.Date createdAtandList<String> items, and make it immutable: afinalclass, all fieldsprivate final, no setters. - In the constructor, check
idwithObjects.requireNonNull(). Store a defensive copy of the date (new Date(createdAt.getTime())) and only after copying check that the date is not in the future. Store the list withList.copyOf()and reject an empty order by throwingIllegalArgumentException. - Write the getters:
getCreatedAt()returns a copy of the date,getItems()returns the field itself. In a comment, explain why the list needs no copy in the getter while theDatedoes. - Instead of a setter, add a
withItem(String item)method that returns a newOrderwith the item added. OverridetoString(). - In
main, prove the class is immutable. After creating an order, change the original list and the original date, callgetCreatedAt().setTime(...)andgetItems().add(...)(expectUnsupportedOperationException), and confirm the order did not change. Then callorder.withItem("jam")first without an assignment and then with one, and compare the output. - Replace
DatewithLocalDateand remove the copies that are no longer needed. In a comment, list which of the five rules of an immutable class now hold by themselves.
Hint
Copy the date before validating it, not after: otherwise another thread can change the original Date between the check and the copy. And do not use createdAt.clone(): Date is not final, so the caller can pass a subclass with an overridden clone().
Record Price: Compact Constructor, Factories and Record Patterns
- Declare
record Price(long cents, String currency): a price in cents and a three-letter currency code. - In the compact constructor, check that
currencyis notnullandcentsis not negative. Convert the currency code to upper case (currency = currency.toUpperCase();) and check that it is exactly three Latin letters. In a comment, explain why you cannot writethis.currency = ...here. - Add an extra constructor
Price(long cents)that passes the currency"EUR"throughthis(...), and a static factoryPrice.zero(String currency). - Add a
plus(Price other)method: it throwsIllegalArgumentExceptionwhen the currencies differ and returns a new price otherwise. - Check the generated methods. Print
new Price(1050, "usd")(expectPrice[cents=1050, currency=USD]). Put two prices with equal components into aHashSetand confirm the set size is 1. - Write a method
String describe(Object o)that uses a record pattern ininstanceof. For a zero price it returns"free (EUR)", for other prices a string like"10.50 USD", and for any other object"not a price".
Nuance
In a compact constructor you assign to the parameter, not to the field: the compiler fills in the fields itself after the constructor body. That is why the normalized currency.toUpperCase() value ends up both in the field and in equals(): new Price(1, "usd") and new Price(1, "USD") are equal.
A Sealed Payment Hierarchy and a switch Without default
- Declare
sealed interface PaymentMethod permits Card, Cash, BankTransfer. MakeCard(String number, boolean premium)andCash()records, makeBankTransfera regular class with thenon-sealedmodifier, and extend it with aSepaTransferclass. - Remove the
non-sealedmodifier fromBankTransfer, write the compiler error (sealed, non-sealed or final modifiers expected) in a comment, and put the modifier back. Explain why the record subtypes need no modifier. - Write a method
long fee(PaymentMethod p, long amount)using aswitchwith pattern matching and nodefault. A premium card costs 0 (a record pattern withwhen), a regular card 2% of the amount, cash 0, and any transfer,SepaTransferincluded, 50. For an amount of 10000 and the four payment methods, the output must be200 0 0 50. - Add a new record
Crypto(String wallet)topermitsand confirm thatfeeno longer compiles (the switch expression does not cover all possible input values). Add a branch forCrypto. In a comment, explain why it is better not to writedefaultin a switch like this. - Try declaring
record GiftCard(String code) implements PaymentMethodwithout adding it topermits, and write the compiler message in a comment.
Hint
The order of the branches matters: case Card(String n, boolean premium) when premium must come before case Card c. If you swap them, the compiler reports this case label is dominated by a preceding case label.
When you write the programs, follow the code style checklist.
How to check your solution
Code that compiles and prints the right result does not yet prove that a class is immutable or that a hierarchy is closed. In these exercises you check a solution by trying to break it: change the object from outside, create an invalid object, add an extra subtype.
Immutable class. After creating the object, change everything you passed to the constructor: the original list, the original date. Change everything the getters returned too. If toString() still prints the same as right after creation, the defensive copies are in place. Trying to change the list through the getter must end with UnsupportedOperationException, not pass silently.
Record. Pass bad data to the constructor: a negative amount, null, the currency "dollars". Each call must throw IllegalArgumentException or NullPointerException with a clear message. Check equality too: new Price(1050, "usd").equals(new Price(1050, "USD")) must be true, because the compact constructor normalizes the currency code.
Sealed hierarchy. Here the compiler does the checking. Add a new type to permits, and the method with a switch that has no default stops compiling until you add a branch for it. If the code still compiles, your switch has a branch left that silently accepts any type.
Frequently asked questions
Which exercise should I start with?
In order: the immutable Order, then record Price, then the sealed payment hierarchy. Each exercise builds on the previous one: a record is a short way to write an immutable class, and the subtypes of the sealed interface in the third exercise are records themselves.
Which Java version do I need?
The first exercise works on Java 10 and later because it uses List.copyOf(). Records need Java 16, sealed classes need Java 17, and a switch with pattern matching, record patterns and when needs Java 21. The easiest choice is to solve all three on Java 21 or 25.
Can I write Order as a record right away in the first exercise?
You can, but then the exercise loses its point: a record makes the class final and the fields private final and has no setters on its own. The exercise is there so you apply all five rules of an immutable class by hand. Once it works, rewrite Order as a record with a defensive copy in the compact constructor and compare the amount of code.
Do interviewers ask exercises like these?
Yes. "How to create an immutable class" is one of the most common Java Core interview questions. Records and sealed classes come up for roles that use Java 17 or later: how a record differs from a regular class and Lombok @Value, why non-sealed exists, and why a switch over a sealed type needs no default.
Comments