← All lessons
Intermediate Java · Lesson 7 of 9

Enums and records

Some values come from a short, fixed list: the days of the week, the suits in a deck, an order's status. Storing them as text invites typos ("shiped"). An enum lists the allowed values, and the compiler rejects anything else.

Java
public class Main {
    enum Status { PENDING, SHIPPED, DELIVERED, CANCELLED }

    static String describe(Status s) {
        return switch (s) {
            case PENDING -> "Waiting to ship";
            case SHIPPED -> "On its way";
            case DELIVERED -> "Arrived";
            case CANCELLED -> "Cancelled";
        };
    }

    public static void main(String[] args) {
        Status s = Status.SHIPPED;
        System.out.println(s);
        System.out.println(describe(s));
        System.out.println(s == Status.SHIPPED);
        System.out.println(Status.valueOf("PENDING").ordinal());
        System.out.println(Status.values().length);
    }
}
Prints
SHIPPED
On its way
true
0
4

Enum values are written in capitals and used as Status.SHIPPED. Each value exists exactly once, so comparing with == is safe. A switch over an enum that covers every value needs no default, and if someone adds a value later the compiler points out every switch that's now missing it. values() lists them all, valueOf turns text into one, and ordinal() is its position.

Enums are classes, so their values can carry fields and methods:

Java
public class Main {
    enum Coin {
        PENNY(1), NICKEL(5), DIME(10), QUARTER(25);

        private final int cents;
        Coin(int cents) { this.cents = cents; }
        int cents() { return cents; }
    }

    public static void main(String[] args) {
        Coin[] pocket = { Coin.QUARTER, Coin.DIME, Coin.DIME, Coin.PENNY };
        int total = 0;
        for (Coin c : pocket) total += c.cents();
        System.out.println(total + " cents");
    }
}
Prints
46 cents

Records

Many classes just hold a few values: a point, a date range, a row of data. Writing the fields, constructor, getters, toString, equals and hashCode by hand is a lot of typing. A record writes them all for you from one line:

Java
public class Main {
    record Point(int x, int y) {
        double distanceToOrigin() { return Math.sqrt(x * x + y * y); }
    }

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println(p);
        System.out.println(p.x() + " " + p.y());
        System.out.println(p.distanceToOrigin());
        Point q = new Point(3, 4);
        System.out.println(p.equals(q));
        System.out.println(p == q);
    }
}
Prints
Point[x=3, y=4]
3 4
5.0
true
false

A record's fields are private and final, so a record can't be changed once made: to "move" a point you make a new one. The getters are named like the fields, p.x(), with no get. And equals compares the contents, so two points with the same x and y are equal even though they're different objects.

A record can check its values in a short constructor with no brackets after the name:

Java
public class Main {
    record Range(int from, int to) {
        Range {
            if (from > to) throw new IllegalArgumentException("from > to");
        }
        int length() { return to - from; }
    }

    public static void main(String[] args) {
        System.out.println(new Range(3, 10).length());
        try {
            new Range(5, 1);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
Prints
7
from > to

equals and hashCode

Why does this matter? HashMap and HashSet find things using two methods every object has: hashCode() (a number that says roughly where to look) and equals() (the final check). A plain class inherits Object's versions, which only treat an object as equal to itself. So two separate objects with the same data count as different keys. Records get versions that compare the contents, which is what you want:

Java
public class Main {
    static class PlainPoint {
        final int x, y;
        PlainPoint(int x, int y) { this.x = x; this.y = y; }
    }
    record Point(int x, int y) {}

    public static void main(String[] args) {
        Set<PlainPoint> a = new HashSet<>();
        a.add(new PlainPoint(1, 2));
        System.out.println(a.contains(new PlainPoint(1, 2)));
        Set<Point> b = new HashSet<>();
        b.add(new Point(1, 2));
        System.out.println(b.contains(new Point(1, 2)));
    }
}
Prints
false
true

If you write equals yourself in a normal class, always write hashCode too, so equal objects give equal hash codes. Or use a record and get both right for free.

Practice

Why use an enum for an order's status instead of a String?

More info

Quick reference

enum Status { A, B, C }A fixed set of named values; compare with ==.
values() / valueOf("A") / ordinal()All values / from text / position from 0.
record P(int x, int y) {}A data class: fields, constructor, getters, toString, equals, hashCode.
p.x()A record's getter (no get).
record R(...) { R { checks } }Check values in a short constructor.
equals / hashCodeHow HashMap and HashSet tell keys apart; override both together.

Related courses