Skip to the workspace
Pebellslearn by building
Object-Oriented Principles  ›  Lesson

Enums and Records

Enums 15 minAn enum is a type with a fixed set of named constants, and a record is a compact, unchangeable data class whose constructor, accessors, equals, hashCode and toString are generated for you.

java / Enums and Records

Explore each scene at your own pace.

01 · The rule

The rule

Enums and Records

An enum is a type with a fixed set of named constants, and a record is a compact, unchangeable data class whose constructor, accessors, equals, hashCode and toString are generated for you.

Represent a fixed set of alternatives with enums and data carriers with records.

Brew Bar's sizes were stored as strings, and one day an order arrived for size "Lrg". Its order lines were ordinary classes with forty lines of constructor, getters and equals code. Two modern Java features fix both problems: enums for a fixed set of choices and records for plain data.

The rule

Fixed choices become an enum; plain data becomes a record.

An enum is a type with a closed list of named values. Nothing else can ever be a Size, so typos cannot compile:

public enum Size {
    SMALL(250), MEDIUM(300), LARGE(350);

    private final int priceCents;

    Size(int priceCents) { this.priceCents = priceCents; }

    public int priceCents() { return priceCents; }
}

Enums can carry fields and methods, as here. Useful built-ins: Size.values() gives all constants in order, Size.valueOf("LARGE") turns text into a constant, name() gives its name and ordinal() its position, counting from 0. Enums also work in switches, and compare safely with == because each constant exists exactly once.

A record is a class whose whole job is to hold some values. One line declares the fields, and Java writes the rest:

public record OrderLine(String drink, Size size, int cups) {
    public OrderLine {                        // compact constructor: validation
        if (cups < 1) throw new IllegalArgumentException("cups must be at least 1");
    }

    public int totalCents() { return size.priceCents() * cups; }
}

From that header, Java generates:

  • private final fields, so a record cannot be changed after creation
  • a constructor taking all three values in order
  • accessor methods named exactly like the fields: drink(), size(), cups(), with no get prefix
  • equals and hashCode that compare the values, and a readable toString, such as OrderLine[drink=Latte, size=LARGE, cups=2]
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.