Enums: A Fixed List of Choices

When there are only a few possible values

Some things only have a few possible values: days of the week, traffic-light colours, T-shirt sizes. An enum lists them, so nobody can use a value that doesn't exist:

enum Light {
    RED, YELLOW, GREEN
}

public class Main {
    public static void main(String[] args) {
        Light now = Light.RED;
        System.out.println(now);

        switch (now) {
            case RED:
                System.out.println("Stop");
                break;
            case YELLOW:
                System.out.println("Get ready");
                break;
            case GREEN:
                System.out.println("Go");
                break;
        }

        for (Light l : Light.values()) {
            System.out.println(l + " is number " + l.ordinal());
        }
    }
}

Output

RED
Stop
RED is number 0
YELLOW is number 1
GREEN is number 2
  • values() gives all the choices, in order.
  • ordinal() gives a choice's position, starting at 0.
  • Light.valueOf("GREEN") turns text into the enum value.

Enums with data

An enum can have fields, a constructor and methods, just like a class:

enum Size {
    SMALL(200), MEDIUM(350), LARGE(500);

    private final int ml;

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

    int getMl() {
        return ml;
    }
}

public class Main {
    public static void main(String[] args) {
        Size s = Size.valueOf("MEDIUM");
        System.out.println(s + " coffee is " + s.getMl() + " ml");
    }
}

Output

MEDIUM coffee is 350 ml

Tip: Prefer an enum over “magic” Strings or numbers like "red" or 2. The compiler catches a typo like Light.GREN; it can't catch "gren".

HOME LABS COMMUNITY DASHBOARD