Enums
An enum is a class whose set of instances is fixed at compile time and listed by name. It is how Java models a value that can only be one of a small, known group, such as an order status.
Detailed Explanation
Before Java 5, a fixed set of choices was written as integer or string constants. An order status was public static final int PENDING = 0; and so on. Nothing stopped you passing 47 where a status was expected. Nothing stopped you passing a customer ID by mistake, because both were just int. Typos in string constants failed at runtime, in production, on a Friday.
An enum fixes this by making the set a type. OrderStatus has exactly four values and the compiler knows all of them. Passing anything else is a compile error, not a bug report.
Each constant is a real object, created once when the enum class is initialised. That means an enum can carry data and behaviour, which is where most learners stop too early. An OrderStatus can hold a display label and a flag for whether it is a terminal state, set through a private constructor. It can declare methods. It can even give each constant its own method body, which turns the enum into a tidy strategy table instead of a switch statement scattered across the codebase.
Because the compiler knows the full list, a switch expression over an enum needs no default branch when every constant is covered. That is a genuine safety feature: add a fifth status later and every exhaustive switch stops compiling until you handle it. A default branch silently defeats this, which is why you should leave it out when you want the compiler to police future changes.
Enums also unlock two specialised collections. EnumMap is backed by a plain array indexed by the constant's position, so lookups are array indexing with no hashing and no collisions. EnumSet is a bit vector; a set of up to 64 constants fits in a single long. Both are faster and smaller than HashMap and HashSet for enum keys, and both iterate in declaration order.
| Need | Reach for |
|---|---|
| A key-value table keyed by enum | EnumMap |
| A set of enum values, membership tests | EnumSet |
| Behaviour that differs per constant | Constant-specific method bodies |
| One instance, ever | A single-constant enum |
That last row is the enum singleton idiom. A one-constant enum gives you lazy class-loading, thread safety, and protection against reflection and serialization attacks for free, which is why it is the recommended way to write a singleton in Java.
The costs are modest but real. Enum constants are loaded eagerly when the class initialises, so a huge enum with heavy constructors delays startup. Enums cannot extend another class, since they already extend java.lang.Enum, though they can implement interfaces. And they are a closed set by design: if third-party code needs to add a case, an interface with implementing classes, or a sealed interface, is the better tool.
Code Examples
public class OrderDemo {
enum OrderStatus {
// Each constant is one object, built once at class initialisation.
PENDING("Waiting for payment", false),
SHIPPED("On the way", false),
DELIVERED("Complete", true),
CANCELLED("Complete", true);
private final String label; // enum state should always be final
private final boolean terminal;
// The constructor is implicitly private; you cannot call it yourself.
OrderStatus(String label, boolean terminal) {
this.label = label;
this.terminal = terminal;
}
public String label() { return label; }
public boolean isTerminal() { return terminal; }
}
// No default branch needed: the compiler sees all four constants are covered.
static int refundWindowDays(OrderStatus status) {
return switch (status) {
case PENDING, CANCELLED -> 0;
case SHIPPED -> 14;
case DELIVERED -> 30;
};
}
public static void main(String[] args) {
// valueOf matches the constant name exactly and throws if it does not exist.
OrderStatus status = OrderStatus.valueOf("SHIPPED");
System.out.println(status.label()); // prints: On the way
System.out.println(refundWindowDays(status)); // prints: 14
System.out.println(status.isTerminal()); // prints: false
}
}import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
class EnumCollections {
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
public static void main(String[] args) {
// EnumMap is an array indexed by ordinal: no hashing, no collisions.
Map<Day, Integer> shiftHours = new EnumMap<>(Day.class);
shiftHours.put(Day.MON, 8);
shiftHours.put(Day.SAT, 0);
// EnumSet is a bit vector. Seven constants fit in a few bits of one long.
EnumSet<Day> weekend = EnumSet.of(Day.SAT, Day.SUN);
System.out.println(shiftHours.get(Day.MON)); // prints: 8
System.out.println(weekend.contains(Day.WED)); // prints: false
System.out.println(shiftHours); // prints: {MON=8, SAT=0}
}
}Common Gotchas
valueOf throws, it does not return null
an unknown name gives `IllegalArgumentException`, and `null` gives `NullPointerException`. When parsing user input or a database column, wrap it in a lookup that returns `Optional`, or catch the exception at the boundary.
Never persist ordinal()
the position of a constant changes the moment someone inserts a new value in the middle, and every stored row silently means something different. Store the `name()` string, or an explicit code field you control.
values() hands back a fresh array every call
the array is mutable, so the JDK defensively copies it each time. Inside a hot loop, cache the result in a private static final array.
Enums are serialization-safe by design
deserialization resolves by name back to the existing constant, so identity comparison with `==` keeps working across a round trip. Ordinary singletons do not get this guarantee.