Stage 2: Object-oriented programming, lesson 7 of 10

Enums in depth

Intermediate3 min read@since 14Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

An enum defines a fixed set of named constants. Each constant is a real object, so enums can have fields, constructors and methods.

  • Built-ins: values(), valueOf("PAID"), name() and ordinal().
  • Enums work in switch, and switch expressions over an enum are checked for completeness.
  • Each constant can override a method, giving you the strategy pattern without extra classes.
  • EnumMap and EnumSet are very fast collections keyed by enum values.
  • An enum with one constant is the simplest thread-safe singleton.

Store enums in databases by name, not by position: @Enumerated(EnumType.STRING) in JPA. Reordering constants would silently corrupt position-based values.

Example

Java
public enum OrderStatus {
    PLACED("Placed"), PAID("Paid"), SHIPPED("On the way"), DELIVERED("Delivered");

    private final String label;
    OrderStatus(String label) { this.label = label; }
    public String label() { return label; }
    public boolean canCancel() { return this == PLACED || this == PAID; }
}

enum Plan {
    FREE { double price() { return 0; } },
    PRO  { double price() { return 499; } };
    abstract double price();                     // each constant implements it
}

String message = switch (status) {               // exhaustive: no default needed
    case PLACED, PAID -> "Preparing your order";
    case SHIPPED -> "On its way";
    case DELIVERED -> "Enjoy!";
};

Map<OrderStatus, Long> counts = new EnumMap<>(OrderStatus.class);
EnumSet<OrderStatus> active = EnumSet.of(OrderStatus.PLACED, OrderStatus.PAID);

Common mistake

Storing ordinal() values. Adding a constant in the middle shifts every number after it and corrupts saved data. Store the name.

Under the hood

Enum constants are created once when the enum class initialises, and the JVM guarantees a single instance per constant even under serialization and reflection, which is why enum singletons are recommended. EnumSet is a bit vector internally and EnumMap an array indexed by position, so both beat HashSet and HashMap for enum keys.

Check yourself

How should JPA store an enum column?

How this connects

Part of Java from zero.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.