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 }SizenullintSIZE_SMALL = 0
Underneath, an enum is an ordinary class with some code generated for it. The program compiles the three-constant Sizejavap
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:
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
class extendingfinal . Because Java has single inheritance, an enum cannot extend another class, but it can implement interfaces.java.lang.Enum<Size> - Each constant is a
field holding the one and only instance, created in the static initializer when the class is loaded.public static final - The compiler added
andvalues() , and a private constructor. Nobody outside can create more instances, and the JVM also blocks it through reflection and deserialization.valueOf(String) providesEnum ,name() (the position, from 0),ordinal() (by ordinal), andcompareTo andequals based on identity.hashCode
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.
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:
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.
returns the constants in declaration order, andvalues() is each one's position in that order.ordinal() converts a name to the constant. It is case-sensitive and throwsvalueOf("EARTH") for unknown names, so parse user input carefully, for example withIllegalArgumentException and a catch.toUpperCase(Locale.ROOT)- Because each constant is a single instance,
is a correct and fast comparison for enums, and it is safe with== on either side, unlikenull .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
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:
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
declares an abstractOp , and each constant has a body that implements it. The compiler turns each body into an anonymous subclass, which is whyapply isOp.ADD.getClass() . UseEnumBehavior$Op$1 when you need the enum type itself.getDeclaringClass() does the same with a lambda passed to the constructor, which is shorter when each constant's behavior fits in one expression.Rounding only searches by name. To look up by another field, such as the symbol "*", build a staticvalueOf once fromMap .values()- The switch expression over
covers all three constants and so needs noLevel . If someone adds a constant, every such switch stops compiling until it handles the new value. Adefault branch would silently swallow it, so leave it out when all cases are handled.default
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
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:
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:
's constructor runs beforeNEW exists.PAID - Moving a shipped order to
was rejected, so impossible states cannot be reached in the program, and the rule is written in one place.CANCELLED stores a set of constants as bits in aEnumSet (for up to 64 constants), andlong stores values in an array indexed by ordinal. Both are faster and smaller thanEnumMap andHashSet , and both iterate in declaration order, as the counts show. SeeHashMapEnumMap 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()
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:
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
, or better, an explicit code field that never changes (name() ), and look it up with a map. JPA'sPAID("P") defaults to@Enumerated , which makes this bug common in database code; useEnumType.ORDINAL .EnumType.STRING 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, storevalues() once in a static field.values()
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. valueOfOptionalnull
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:
'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
produced "unknown currency" without an exception. The caller decides what an unknown value means, which is usually a validation error with a clear message.null - The constant names (
) 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.US_DOLLAR failed because no constant is namedvalueOf("USD") ; the message names the enum and the value it was given.USD- When upper-casing for a lookup, pass
. In a Turkish locale,Locale.ROOT is the dotted capital"i".toUpperCase() , so "fixed_price" became "FİXED_PRİCE" and would not match a constant namedİ . This bug has appeared in many real applications that ran fine everywhere except on Turkish machines.FIXED_PRICE
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.
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:
2 + 5 = 7.0
2 * 5 = 10.0
2 ^ 5 = 32.0
2 max 5 = 5.0
- The loop only knows about
, 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).Operation - Each enum still keeps the benefits of an enum for its own constants: a fixed set,
,values() and safeEnumSet .== - The trade-off is that a
overswitch 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.Operation
When to use an enum
| Need | Use |
|---|---|
| A fixed set of named values known at compile time | An enum |
| Values loaded from a database or configuration | A class or record, not an enum |
| Values that each need different data shapes | A sealed interface with records ( |
| A set of options | EnumSetint |
| A map keyed by an enum | EnumMap |
| Storing an enum value | Its name or an explicit code, never ordinal() |
| A singleton | A single-constant enum |
Enums can also implement