Enums in Java

An enum is a class with a fixed set of instances, written as a list of constants. Since Java 5, enums are full classes: they can have fields, constructors, methods and even a different implementation per constant, and the compiler checks that a switch handles every value. This page shows what an enum compiles to, the ways to give constants data and behavior, real uses such as state machines and singletons, and the ordinal mistake that corrupts stored data.

Contents

What an enum is

An enum type defines a closed set of values: enum Size { SMALL, MEDIUM, LARGE } means a Size can only ever be one of those three objects, or null. Before Java 5, programs used int constants such as SIZE_SMALL = 0, which allowed any integer, printed as a meaningless number and gave no type checking. An enum fixes all three problems.

Underneath, an enum is an ordinary class with some code generated for it. The program compiles the three-constant Size enum and lists its members with javap.

Java
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.spi.ToolProvider;

// Compiles a three-constant enum and lists what javac generated, using javap
public class WhatAnEnumIs {

    static final String SOURCE = """
            enum Size { SMALL, MEDIUM, LARGE }
            """;

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("enum");
        Files.writeString(dir.resolve("Size.java"), SOURCE);
        run("javac", "-d", dir.toString(), dir.resolve("Size.java").toString());
        run("javap", "-p", "-cp", dir.toString(), "Size").lines()
                .filter(l -> !l.startsWith("Compiled from"))
                .forEach(System.out::println);
    }

    static String run(String tool, String... args) {
        StringWriter out = new StringWriter();
        PrintWriter pw = new PrintWriter(out);
        ToolProvider.findFirst(tool).orElseThrow().run(pw, pw, args);
        pw.flush();
        return out.toString();
    }
}

Output:

Output
final class Size extends java.lang.Enum<Size> {
  public static final Size SMALL;
  public static final Size MEDIUM;
  public static final Size LARGE;
  private static final Size[] $VALUES;
  public static Size[] values();
  public static Size valueOf(java.lang.String);
  private Size();
  private static Size[] $values();
  static {};
}
  • The enum became a final class extending java.lang.Enum<Size>. Because Java has single inheritance, an enum cannot extend another class, but it can implement interfaces.
  • Each constant is a public static final field holding the one and only instance, created in the static initializer when the class is loaded.
  • The compiler added values() and valueOf(String), and a private constructor. Nobody outside can create more instances, and the JVM also blocks it through reflection and deserialization.
  • Enum provides name(), ordinal() (the position, from 0), compareTo (by ordinal), and equals and hashCode based on identity.

Fields, constructors and methods

Each constant can pass arguments to a constructor, so it carries data. The program uses the planet example from the Java documentation: each planet stores its mass and radius, and a method computes its surface gravity. Earth's 9.80 m/s² is a value most readers know, which makes the output easy to check.

Java
import java.util.Arrays;

public class EnumBasics {

    enum Planet {
        MERCURY(3.303e+23, 2.4397e6),
        EARTH(5.976e+24, 6.37814e6),
        JUPITER(1.9e+27, 7.1492e7);

        private static final double G = 6.67300E-11;
        private final double mass;     // kg
        private final double radius;   // m

        Planet(double mass, double radius) {     // constructors are always private
            this.mass = mass;
            this.radius = radius;
        }

        double surfaceGravity() {
            return G * mass / (radius * radius);
        }
    }

    public static void main(String[] args) {
        for (Planet p : Planet.values()) {
            System.out.printf("%-8s ordinal %d, gravity %5.2f m/s^2%n",
                    p, p.ordinal(), p.surfaceGravity());
        }
        System.out.println("valueOf(\"EARTH\"): " + Planet.valueOf("EARTH"));
        try {
            Planet.valueOf("Earth");
        } catch (IllegalArgumentException e) {
            System.out.println("valueOf(\"Earth\"): " + e.getMessage());
        }
        System.out.println("EARTH.compareTo(JUPITER): " + Planet.EARTH.compareTo(Planet.JUPITER));
        System.out.println("== is safe for enums: " + (Planet.valueOf("EARTH") == Planet.EARTH));
        System.out.println("names: " + Arrays.toString(Planet.values()));
    }
}

Output:

Output
MERCURY  ordinal 0, gravity  3.70 m/s^2
EARTH    ordinal 1, gravity  9.80 m/s^2
JUPITER  ordinal 2, gravity 24.81 m/s^2
valueOf("EARTH"): EARTH
valueOf("Earth"): No enum constant EnumBasics.Planet.Earth
EARTH.compareTo(JUPITER): -1
== is safe for enums: true
names: [MERCURY, EARTH, JUPITER]
  • Enum constructors are always private, whether or not the keyword is written. They run once per constant when the enum is first used.
  • values() returns the constants in declaration order, and ordinal() is each one's position in that order.
  • valueOf("EARTH") converts a name to the constant. It is case-sensitive and throws IllegalArgumentException for unknown names, so parse user input carefully, for example with toUpperCase(Locale.ROOT) and a catch.
  • Because each constant is a single instance, == is a correct and fast comparison for enums, and it is safe with null on either side, unlike equals.

Behavior per constant, lookup by field, and exhaustive switch

Constants can do more than hold data: each can have its own method implementation. The program builds a small calculator where every operation is a constant, looks an operation up by its symbol, and switches over a severity level without a default.

Java
import java.util.Map;
import java.util.function.IntBinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EnumBehavior {

    // Each constant supplies its own implementation
    enum Op {
        ADD("+") {
            @Override
            int apply(int a, int b) {
                return a + b;
            }
        },
        MULTIPLY("*") {
            @Override
            int apply(int a, int b) {
                return a * b;
            }
        };

        private final String symbol;

        Op(String symbol) {
            this.symbol = symbol;
        }

        abstract int apply(int a, int b);
    }

    // The same idea with a lambda field instead of constant-specific bodies
    enum Rounding {
        DOWN((a, b) -> Math.floorDiv(a, b)),
        UP((a, b) -> -Math.floorDiv(-a, b));

        private final IntBinaryOperator fn;

        Rounding(IntBinaryOperator fn) {
            this.fn = fn;
        }

        int divide(int a, int b) {
            return fn.applyAsInt(a, b);
        }
    }

    enum Level { LOW, MEDIUM, HIGH }

    // Look up by a field instead of by name
    static final Map<String, Op> BY_SYMBOL = Stream.of(Op.values())
            .collect(Collectors.toMap(op -> op.symbol, op -> op));

    static String advice(Level level) {
        return switch (level) {                 // exhaustive: no default needed
            case LOW -> "ignore";
            case MEDIUM -> "watch";
            case HIGH -> "act now";
        };
    }

    public static void main(String[] args) {
        for (Op op : Op.values()) {
            System.out.println("6 " + op.symbol + " 7 = " + op.apply(6, 7));
        }
        System.out.println("lookup \"*\": " + BY_SYMBOL.get("*"));
        System.out.println("7 / 2 rounded DOWN = " + Rounding.DOWN.divide(7, 2)
                + ", UP = " + Rounding.UP.divide(7, 2));
        for (Level l : Level.values()) {
            System.out.println(l + " -> " + advice(l));
        }
        System.out.println("ADD's class: " + Op.ADD.getClass().getName()
                + ", declaring: " + Op.ADD.getDeclaringClass().getSimpleName());
    }
}

Output:

Output
6 + 7 = 13
6 * 7 = 42
lookup "*": MULTIPLY
7 / 2 rounded DOWN = 3, UP = 4
LOW -> ignore
MEDIUM -> watch
HIGH -> act now
ADD's class: EnumBehavior$Op$1, declaring: Op
  • Op declares an abstract apply, and each constant has a body that implements it. The compiler turns each body into an anonymous subclass, which is why Op.ADD.getClass() is EnumBehavior$Op$1. Use getDeclaringClass() when you need the enum type itself.
  • Rounding does the same with a lambda passed to the constructor, which is shorter when each constant's behavior fits in one expression.
  • valueOf only searches by name. To look up by another field, such as the symbol "*", build a static Map once from values().
  • The switch expression over Level covers all three constants and so needs no default. If someone adds a constant, every such switch stops compiling until it handles the new value. A default branch would silently swallow it, so leave it out when all cases are handled.

State machines, EnumSet, EnumMap and singletons

An order that moves through states is a natural enum. The program stores the allowed transitions on each state, moves an order through a valid path, rejects an invalid move, counts orders per state with an EnumMap, and finishes with the enum singleton.

Java
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class StateMachine {

    enum Status {
        NEW, PAID, SHIPPED, DELIVERED, CANCELLED;

        // Allowed next states, defined after all constants exist
        private Set<Status> next;

        static {
            NEW.next = EnumSet.of(PAID, CANCELLED);
            PAID.next = EnumSet.of(SHIPPED, CANCELLED);
            SHIPPED.next = EnumSet.of(DELIVERED);
            DELIVERED.next = EnumSet.noneOf(Status.class);
            CANCELLED.next = EnumSet.noneOf(Status.class);
        }

        Status moveTo(Status target) {
            if (!next.contains(target)) {
                throw new IllegalStateException(this + " cannot move to " + target);
            }
            return target;
        }

        boolean isFinal() {
            return next.isEmpty();
        }
    }

    // A singleton: the JVM guarantees exactly one instance, even with serialization
    enum Registry {
        INSTANCE;

        private int registrations;

        int register() {
            return ++registrations;
        }
    }

    public static void main(String[] args) {
        Status s = Status.NEW;
        for (Status target : List.of(Status.PAID, Status.SHIPPED, Status.DELIVERED)) {
            s = s.moveTo(target);
            System.out.println("moved to " + s + (s.isFinal() ? " (final)" : ""));
        }
        try {
            Status.SHIPPED.moveTo(Status.CANCELLED);
        } catch (IllegalStateException e) {
            System.out.println("rejected: " + e.getMessage());
        }

        // EnumMap: a map keyed by an enum, stored as an array indexed by ordinal
        Map<Status, Integer> counts = new EnumMap<>(Status.class);
        for (Status st : List.of(Status.PAID, Status.NEW, Status.PAID, Status.CANCELLED)) {
            counts.merge(st, 1, Integer::sum);
        }
        System.out.println("counts (in declaration order): " + counts);
        System.out.println("final states: " + EnumSet.of(Status.DELIVERED, Status.CANCELLED));
        System.out.println("open states: "
                + EnumSet.complementOf(EnumSet.of(Status.DELIVERED, Status.CANCELLED)));

        Registry.INSTANCE.register();
        System.out.println("registrations: " + Registry.INSTANCE.register());
    }
}

Output:

Output
moved to PAID
moved to SHIPPED
moved to DELIVERED (final)
rejected: SHIPPED cannot move to CANCELLED
counts (in declaration order): {NEW=1, PAID=2, CANCELLED=1}
final states: [DELIVERED, CANCELLED]
open states: [NEW, PAID, SHIPPED]
registrations: 2
  • The transitions are set in a static block because a constant cannot refer to constants declared after it while being constructed: NEW's constructor runs before PAID exists.
  • Moving a shipped order to CANCELLED was rejected, so impossible states cannot be reached in the program, and the rule is written in one place.
  • EnumSet stores a set of constants as bits in a long (for up to 64 constants), and EnumMap stores values in an array indexed by ordinal. Both are faster and smaller than HashSet and HashMap, and both iterate in declaration order, as the counts show. See EnumMap and EnumSet.
  • An enum with one constant is the simplest correct singleton: the JVM guarantees one instance even across serialization and reflection, which hand-written singletons must defend against. Its state, here a counter, is shared by the whole program, with the usual cautions about threads.

The ordinal trap

ordinal() is tempting to store, because it is a small number. But it is just the position in the source code. The program simulates orders saved with one version of an enum and read back after a developer added a constant in the middle.

Java
import java.util.List;

public class OrdinalTrap {

    // Version 1 of an enum, as it was when data was saved
    enum StatusV1 { NEW, PAID, SHIPPED }

    // Version 2: someone added CANCELLED in the middle
    enum StatusV2 { NEW, CANCELLED, PAID, SHIPPED }

    public static void main(String[] args) {
        // Orders saved with version 1, storing ordinal() and name()
        List<StatusV1> saved = List.of(StatusV1.PAID, StatusV1.SHIPPED);
        for (StatusV1 s : saved) {
            StatusV2 byOrdinal = StatusV2.values()[s.ordinal()];
            StatusV2 byName = StatusV2.valueOf(s.name());
            System.out.printf("saved %-7s -> read back by ordinal: %-9s by name: %s%n",
                    s, byOrdinal, byName);
        }

        // values() returns a new array every call, because arrays are mutable
        System.out.println("values() == values(): " + (StatusV2.values() == StatusV2.values()));
        StatusV2[] copy = StatusV2.values();
        copy[0] = null;                                 // cannot damage the enum
        System.out.println("after changing the copy: " + StatusV2.values()[0]);
    }
}

Output:

Output
saved PAID    -> read back by ordinal: CANCELLED by name: PAID
saved SHIPPED -> read back by ordinal: PAID      by name: SHIPPED
values() == values(): false
after changing the copy: NEW
  • Reading by ordinal turned a paid order into a cancelled one and a shipped order into a paid one, with no error at all. Reading by name gave the right answers.
  • Store name(), or better, an explicit code field that never changes (PAID("P")), and look it up with a map. JPA's @Enumerated defaults to EnumType.ORDINAL, which makes this bug common in database code; use EnumType.STRING.
  • values() returns a new array each time, because the caller could change an array. Changing the copy did not affect the enum. In a hot loop, store values() once in a static field.

Parsing enums from text safely

Enum values often arrive as text: a currency code in a JSON request, a status in a CSV file, a command-line option. valueOf is a poor fit for such input, because it matches only the exact constant name and throws on anything else. The program adds a lookup by an external code that tolerates case and spaces and returns an Optional instead of throwing. The inputs include lower case, padding, an unknown code and null.

Java
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ParsingEnums {

    enum Currency {
        US_DOLLAR("USD", 2), EURO("EUR", 2), YEN("JPY", 0);

        private static final Map<String, Currency> BY_CODE = Arrays.stream(values())
                .collect(Collectors.toUnmodifiableMap(c -> c.code, Function.identity()));

        private final String code;
        private final int decimals;

        Currency(String code, int decimals) {
            this.code = code;
            this.decimals = decimals;
        }

        // Lookup by an external code, tolerant of case, with no exception for unknown input
        static Optional<Currency> fromCode(String text) {
            if (text == null) {
                return Optional.empty();
            }
            return Optional.ofNullable(BY_CODE.get(text.strip().toUpperCase(Locale.ROOT)));
        }
    }

    public static void main(String[] args) {
        for (String input : new String[] {"usd", " EUR ", "JPY", "GBP", null}) {
            String result = Currency.fromCode(input)
                    .map(c -> c + " (" + c.decimals + " decimals)")
                    .orElse("unknown currency");
            System.out.printf("%-7s -> %s%n", input == null ? "null" : "'" + input + "'", result);
        }

        // valueOf matches the constant NAME exactly
        try {
            Currency.valueOf("USD");
        } catch (IllegalArgumentException e) {
            System.out.println("valueOf(\"USD\"): " + e.getMessage());
        }
        // Upper-casing for a lookup needs Locale.ROOT: in Turkish, "i" becomes a dotted capital
        String name = "fixed_price";
        System.out.println("Turkish locale: " + name.toUpperCase(Locale.of("tr"))
                + ", Locale.ROOT: " + name.toUpperCase(Locale.ROOT));
    }
}

Output:

Output
'usd'   -> US_DOLLAR (2 decimals)
' EUR ' -> EURO (2 decimals)
'JPY'   -> YEN (0 decimals)
'GBP'   -> unknown currency
null    -> unknown currency
valueOf("USD"): No enum constant ParsingEnums.Currency.USD
Turkish locale: FİXED_PRİCE, Locale.ROOT: FIXED_PRICE
  • "usd", " EUR " and "JPY" were all found, and "GBP" and null produced "unknown currency" without an exception. The caller decides what an unknown value means, which is usually a validation error with a clear message.
  • The constant names (US_DOLLAR) and the external codes ("USD") are separate. That lets the codes follow a standard, here ISO 4217, while the Java names stay readable, and it means renaming a constant cannot break stored data or an API.
  • valueOf("USD") failed because no constant is named USD; the message names the enum and the value it was given.
  • When upper-casing for a lookup, pass Locale.ROOT. In a Turkish locale, "i".toUpperCase() is the dotted capital İ, so "fixed_price" became "FİXED_PRİCE" and would not match a constant named FIXED_PRICE. This bug has appeared in many real applications that ran fine everywhere except on Turkish machines.

Making enum-based code extensible with an interface

An enum is closed: nobody outside it can add a constant. When other code should be able to add values, for example plugins adding operations to a calculator, put the behavior in an interface and let enums implement it. The program has a basic operations enum, an extended one, and a record defined by "a third party", all used through the same interface.

Java
import java.util.List;

public class ExtensibleEnum {

    // Code depends on the interface, so other enums or classes can add operations
    interface Operation {
        double apply(double x, double y);

        String symbol();
    }

    enum BasicOp implements Operation {
        PLUS("+") {
            public double apply(double x, double y) {
                return x + y;
            }
        },
        TIMES("*") {
            public double apply(double x, double y) {
                return x * y;
            }
        };

        private final String symbol;

        BasicOp(String symbol) {
            this.symbol = symbol;
        }

        @Override
        public String symbol() {
            return symbol;
        }
    }

    enum ExtendedOp implements Operation {
        POWER("^") {
            public double apply(double x, double y) {
                return Math.pow(x, y);
            }
        };

        private final String symbol;

        ExtendedOp(String symbol) {
            this.symbol = symbol;
        }

        @Override
        public String symbol() {
            return symbol;
        }
    }

    // A third party can add an operation without touching either enum
    record Custom(String symbol) implements Operation {
        @Override
        public double apply(double x, double y) {
            return Math.max(x, y);
        }
    }

    public static void main(String[] args) {
        List<Operation> ops = List.of(BasicOp.PLUS, BasicOp.TIMES, ExtendedOp.POWER,
                new Custom("max"));
        for (Operation op : ops) {
            System.out.printf("2 %s 5 = %s%n", op.symbol(), op.apply(2, 5));
        }
    }
}

Output:

Output
2 + 5 = 7.0
2 * 5 = 10.0
2 ^ 5 = 32.0
2 max 5 = 5.0
  • The loop only knows about Operation, so it handled constants from two different enums and a record the same way. This is the "extensible enum" pattern from Effective Java (item 38).
  • Each enum still keeps the benefits of an enum for its own constants: a fixed set, values(), EnumSet and safe ==.
  • The trade-off is that a switch over Operation can no longer be exhaustive, because new implementations can appear. If the set of implementations should be fixed but each needs its own data, a sealed interface is the better tool.

When to use an enum

Enums compared with alternatives
NeedUse
A fixed set of named values known at compile timeAn enum
Values loaded from a database or configurationA class or record, not an enum
Values that each need different data shapesA sealed interface with records (sealed classes)
A set of optionsEnumSet, not int bit flags
A map keyed by an enumEnumMap
Storing an enum valueIts name or an explicit code, never ordinal()
A singletonA single-constant enum

Enums can also implement interfaces, which lets code accept "any operation" while some operations are enum constants and others come from elsewhere.