JAVA-102 · Lesson 9 of 12 · 21 min
Enums and records
▶ Video coming soon A video version of this lesson is on the way.
Two weaknesses have survived every lesson so far. The booking status is a String, so a typo such as "CONFIMED" compiles happily and breaks the rules silently. And small classes that only carry values, such as a time slot or a receipt line, take twenty lines of constructor, getters, equals and toString each. The plan for Wednesday, March 17, 2027 is to fix both with two special kinds of class Java added for exactly these jobs: enums for fixed sets of named values, and records for small immutable data carriers.
Enums
An enum (short for enumerated type) is a class with a fixed list of instances, declared by name. enum Status { REQUESTED, CONFIRMED, READY, PICKED_UP, WITHDRAWN } creates a type Status with exactly five possible values, written Status.CONFIRMED and so on. A variable of type Status can hold only one of those five, or null. A misspelled value does not compile.
public class Main {
enum Status { REQUESTED, CONFIRMED, READY, PICKED_UP, WITHDRAWN }
public static void main(String[] args) {
Status s = Status.REQUESTED;
System.out.println("Starts as " + s);
s = Status.CONFIRMED;
System.out.println("Now " + s + ", position " + s.ordinal());
System.out.println("Is it ready? " + (s == Status.READY));
System.out.println("All statuses:");
for (Status each : Status.values()) {
System.out.println(" " + each);
}
System.out.println("From text: " + Status.valueOf("PICKED_UP"));
}
}Starts as REQUESTED Now CONFIRMED, position 1 Is it ready? false All statuses: REQUESTED CONFIRMED READY PICKED_UP WITHDRAWN From text: PICKED_UP
What this code does
Status has exactly five values, and a variable of type Status can hold only those. Enum values print as their names, compare safely with ==, and know their position through ordinal. values() lists them all in declaration order, and valueOf turns matching text back into a value.
Comparing enums with == is correct and safe, unlike Strings, because there is exactly one object for each value. Status.valueOf("CONFIMED") with a typo throws IllegalArgumentException, which makes enums a good way to check text that should be one of a few known values. Avoid relying on ordinal() for anything stored or important, because adding a value in the middle changes the numbers.
Enums in switch
Enums and switch fit naturally. In a switch on an enum, case labels use the bare value names. A switch expression over an enum that covers every value needs no default, and javac reports an error if a value is missing, just as with sealed types in lesson 7.
public class Main {
enum Status { REQUESTED, CONFIRMED, READY, PICKED_UP, WITHDRAWN }
public static void main(String[] args) {
for (Status s : Status.values()) {
System.out.println(s + ": " + nextStep(s));
}
}
static String nextStep(Status s) {
return switch (s) {
case REQUESTED -> "call the customer to confirm";
case CONFIRMED -> "do the repair";
case READY -> "wait for pickup";
case PICKED_UP, WITHDRAWN -> "nothing; booking closed";
};
}
}REQUESTED: call the customer to confirm CONFIRMED: do the repair READY: wait for pickup PICKED_UP: nothing; booking closed WITHDRAWN: nothing; booking closed
What this code does
Each case names an enum value without the Status prefix, and one case can list several values separated by commas. The switch expression covers all five values, so no default is needed. If a sixth status were added, this switch would stop compiling until it was handled.
Enums with fields and methods
An enum is a full class, so it can have fields, a constructor and methods. Each value passes arguments to the constructor in parentheses after its name. The constructor is always private, since nobody else may create values. This lets each value carry its own data, such as a label for the screen, and lets the enum hold the rules about its values, such as which status may follow which.
public class Main {
public static void main(String[] args) {
Status s = Status.REQUESTED;
System.out.println(s.label());
s = s.moveTo(Status.CONFIRMED);
s = s.moveTo(Status.READY);
System.out.println(s.label() + ", closed? " + s.isClosed());
try {
s.moveTo(Status.REQUESTED);
} catch (IllegalStateException e) {
System.out.println("Refused: " + e.getMessage());
}
}
}
enum Status {
REQUESTED("Requested", false),
CONFIRMED("Confirmed", false),
READY("Ready for pickup", false),
PICKED_UP("Picked up", true),
WITHDRAWN("Withdrawn by customer", true);
private final String label;
private final boolean closed;
Status(String label, boolean closed) {
this.label = label;
this.closed = closed;
}
String label() { return label; }
boolean isClosed() { return closed; }
boolean canMoveTo(Status next) {
return switch (this) {
case REQUESTED -> next == CONFIRMED || next == WITHDRAWN;
case CONFIRMED -> next == READY || next == WITHDRAWN;
case READY -> next == PICKED_UP;
case PICKED_UP, WITHDRAWN -> false;
};
}
Status moveTo(Status next) {
if (!canMoveTo(next)) {
throw new IllegalStateException(this + " cannot move to " + next);
}
return next;
}
}Requested Ready for pickup, closed? false Refused: READY cannot move to REQUESTED
What this code does
Each value gives the private constructor a label and whether the booking is closed. canMoveTo holds Odile's rules about which status may follow which, so every class that changes a status uses the same rules. moveTo throws IllegalStateException for a move the rules forbid, such as from READY back to REQUESTED.
The status rules are now a state machine written in one enum: a fixed set of states and the allowed moves between them. Booking no longer needs its own checks; its confirm method can simply call status = status.moveTo(Status.CONFIRMED).
Enums can implement interfaces and have per-value behaviour
Because enums are classes, they can implement interfaces, and each value can even override a method with its own body. The rental fleet's bike types differ in daily rate and deposit, and an enum makes each type's numbers and rules part of the type itself.
public class Main {
public static void main(String[] args) {
for (BikeType t : BikeType.values()) {
System.out.printf("%-6s day %5d deposit %6d 3 days %6d%n",
t, t.dailyCents(), t.depositCents(), t.priceFor(3));
}
}
}
interface Priced {
long priceFor(int days);
}
enum BikeType implements Priced {
CITY(1500, 2500),
CARGO(3000, 10000),
TANDEM(2500, 7500) {
@Override
public long priceFor(int days) {
return Math.max(2, days) * dailyCents(); // tandems rent for at least 2 days
}
};
private final long dailyCents;
private final long depositCents;
BikeType(long dailyCents, long depositCents) {
this.dailyCents = dailyCents;
this.depositCents = depositCents;
}
long dailyCents() { return dailyCents; }
long depositCents() { return depositCents; }
@Override
public long priceFor(int days) {
return dailyCents * (days - days / 7);
}
}CITY day 1500 deposit 2500 3 days 4500 CARGO day 3000 deposit 10000 3 days 9000 TANDEM day 2500 deposit 7500 3 days 7500
What this code does
BikeType implements Priced, and each value carries its daily rate and deposit. TANDEM has a body of its own that overrides priceFor with a two-day minimum, while the other values use the shared version. The loop prints each type's figures without any if statements about types.
Records
A record, final in Java 16, is a concise way to declare a class whose job is to carry a fixed set of values. You write the record's name and its components in parentheses, and Java generates the rest: a private final field for each component, a constructor that takes them all, an accessor method for each, named after the component without get, and equals, hashCode and toString methods based on all the components.
public class Main {
record Slot(String date, int hour) { }
public static void main(String[] args) {
Slot a = new Slot("2027-04-03", 9);
Slot b = new Slot("2027-04-03", 9);
Slot c = new Slot("2027-04-03", 14);
System.out.println(a);
System.out.println("Hour: " + a.hour());
System.out.println("a equals b? " + a.equals(b));
System.out.println("a equals c? " + a.equals(c));
System.out.println("Same hash for a and b? " + (a.hashCode() == b.hashCode()));
}
}Slot[date=2027-04-03, hour=9] Hour: 9 a equals b? true a equals c? false Same hash for a and b? true
What this code does
The one-line record declares a complete immutable class with two components. Its generated toString shows the component names and values, and the accessors are date() and hour(). The generated equals compares the components, so a and b are equal even though they are different objects, and equal records have equal hash codes.
Compare that with the Slot class of lesson 1, which needed fields, a constructor and a sameTimeAs method and still did not have a proper equals. A record is the right choice whenever a class is just its data: the values are fixed when it is made, and two objects with the same values should count as equal.
Compact constructors and validation
A record can check its components in a compact constructor, a constructor written with just the record's name and no parameter list. The parameters are the components, and the body runs before they are stored in the fields, so it can validate or normalize them. Throwing from it prevents invalid records from ever existing.
public class Main {
record Slot(String date, int hour) {
Slot {
if (hour < 9 || hour > 16) {
throw new IllegalArgumentException("the shop takes repairs from 9 to 16, not " + hour);
}
date = date.strip();
}
String label() {
return date + " at " + hour + ":00";
}
Slot nextHour() {
return new Slot(date, hour + 1);
}
}
public static void main(String[] args) {
Slot s = new Slot(" 2027-04-03 ", 15);
System.out.println(s.label());
System.out.println(s.nextHour().label());
try {
s.nextHour().nextHour();
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}2027-04-03 at 15:00 2027-04-03 at 16:00 Rejected: the shop takes repairs from 9 to 16, not 17
What this code does
The compact constructor checks the hour and strips spaces from the date before the fields are set, so every Slot is valid and tidy. Records can have ordinary methods such as label, and because they are immutable, nextHour returns a new Slot instead of changing this one. Asking for a slot at 17 throws, so the invalid slot is never created.
What records can and cannot do
Records are deliberately limited, and the limits are what make them simple to reason about.
| Records can | Records cannot |
|---|---|
| Have methods, static fields and static methods | Have instance fields other than their components |
| Implement interfaces | Extend another class (they implicitly extend Record) |
| Validate in a compact constructor | Change their components after creation |
| Add extra constructors that call the canonical one with this(...) | Be extended: records are implicitly final |
| Be nested in a class, and be used in record patterns | Hide their components: accessors are always public |
One trap remains from lesson 2: a record's fields are final, but if a component is a mutable object, such as an array, its contents can still change. Prefer immutable component types, or copy arrays in the compact constructor.
public class Main {
record ReceiptLine(String item, int qty, long unitCents) {
ReceiptLine {
if (qty <= 0) throw new IllegalArgumentException("qty must be positive");
}
long totalCents() { return qty * unitCents; }
}
record Receipt(String customer, ReceiptLine[] lines) {
Receipt {
lines = lines.clone();
}
long totalCents() {
long t = 0;
for (ReceiptLine l : lines) t += l.totalCents();
return t;
}
}
public static void main(String[] args) {
ReceiptLine[] lines = {
new ReceiptLine("700x25c inner tube", 2, 899),
new ReceiptLine("tube install", 1, 1000),
};
Receipt r = new Receipt("Ana Ruiz", lines);
lines[0] = new ReceiptLine("gold chain", 1, 99999);
System.out.println(r.customer() + ": " + r.totalCents() + " cents");
for (ReceiptLine l : r.lines()) {
System.out.println(" " + l.qty() + " x " + l.item() + " = " + l.totalCents());
}
}
}Ana Ruiz: 2798 cents 2 x 700x25c inner tube = 1798 1 x tube install = 1000
What this code does
Receipt copies the array in its compact constructor, so replacing an element of the caller's array afterwards does not change the receipt. Each ReceiptLine validates its quantity and works out its own total. The accessor lines() still returns the stored array itself, so a fully careful record would copy on the way out too, or use an immutable List from JAVA-120.
Choosing between a class, an enum and a record
With three kinds of type available, the choice usually follows from the job.
| Use | When | Booking system example |
|---|---|---|
| enum | There is a fixed, known set of values | Status, BikeType |
| record | The type is just its data, fixed at creation, compared by value | Slot, ReceiptLine, Money |
| class | The object has identity and state that changes over time | Booking, whose status changes |
| sealed interface with records | A fixed set of kinds, each with different data | RepairBooking and RentalBooking |
Try it yourself
An enum with a field
Give the enum Size a field frameCm set through a constructor: SMALL 50, MEDIUM 54, LARGE 58.
Add a method fits(int heightCm) that returns true when the frame is between 0.32 and 0.36 of the height, inclusive. Print each size, then the first size that fits a rider who is 165 cm tall. The program should print SMALL 50 cm, MEDIUM 54 cm, LARGE 58 cm and then For 165 cm: MEDIUM.
public class Main {
enum Size { SMALL, MEDIUM, LARGE }
public static void main(String[] args) {
for (Size s : Size.values()) {
System.out.println(s + " cm");
}
System.out.println("For 165 cm: ?");
}
}Try it yourself
A validating record
Write a record Deposit(String customer, long cents) whose compact constructor throws IllegalArgumentException with the message deposit must be at least 1000 cents when cents is under 1000, and strips spaces from the customer name.
The program should print Deposit[customer=Theo Park, cents=2500] and Rejected: deposit must be at least 1000 cents.
public class Main {
record Deposit(String customer, long cents) { }
public static void main(String[] args) {
System.out.println(new Deposit(" Theo Park ", 2500));
try {
System.out.println(new Deposit("Mei Lin", 500));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}Common mistakes
MistakeUsing Strings such as "CONFIRMED" for a fixed set of states.
InsteadUse an enum so typos do not compile and switches can be checked.
MistakeStoring or relying on an enum's ordinal().
InsteadUse the name or a field of the enum; ordinals change when values are added.
MistakeWriting get in record accessor names, as slot.getHour().
InsteadRecord accessors are named after the components: slot.hour().
MistakeTrying to change a record's component after creation.
InsteadRecords are immutable; return a new record with the changed value.
MistakeValidating record components in a separate method that callers may forget.
InsteadCheck them in the compact constructor so invalid records cannot exist.
Summary and key terms
- An enum is a class with a fixed list of named instances; enum variables hold only those values, compare safely with ==, and offer values(), valueOf and ordinal.
- Switch works naturally with enums and, as a switch expression covering every value, needs no default.
- Enums can have fields, a private constructor and methods, implement interfaces and give individual values their own method bodies, which makes them a good home for a state machine such as the booking status.
- A record declares an immutable data class in one line, generating fields, a constructor, accessors named after the components and value-based equals, hashCode and toString.
- A compact constructor validates or normalizes components before they are stored.
- Records can have methods and implement interfaces but cannot extend classes, add instance fields or be changed.
- Use enums for fixed sets of values, records for data compared by value, and ordinary classes for objects with changing state.
- Enum
- A type with a fixed set of named instances.
- values()
- The static method that returns all of an enum's values in order.
- valueOf
- The static method that turns a value's name into the enum value.
- ordinal()
- An enum value's position in the declaration, starting at 0.
- State machine
- A fixed set of states with rules about the allowed moves between them.
- Record
- A concise immutable class whose state is a fixed list of components.
- Component
- One of the values a record is declared with.
- Accessor
- A generated method that returns a record component, named after it.
- Canonical constructor
- The record constructor that takes every component.
- Compact constructor
- A record constructor without a parameter list that validates components before they are stored.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why does Status.CONFIMED fail to compile when Status is an enum?
Show answer
CONFIMED is not one of the declared values.
Why is == safe for comparing enum values?
Show answer
There is exactly one object for each value.
What does the record declaration record Slot(String date, int hour) {} generate?
Show answer
Private final fields, a constructor, accessors date() and hour(), and equals, hashCode and toString.
When does the body of a compact constructor run?
Show answer
Before the components are stored in the fields.
Should Booking, whose status changes, be a record?
Show answer
No; records are immutable, so a changing object should be an ordinary class.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.