An enum (short for “enumeration”) defines a fixed, named set of constants. Use it whenever a value should only ever be one of a small, known list of options.
Tip: reach for an enum instead of a plain String whenever a value has a fixed set of valid options, like a day of the week or an order status — it lets the compiler catch typos for you.
Defining an enum
public enum OrderStatus {
PENDING,
SHIPPED,
DELIVERED,
CANCELLED
}
Using an enum
OrderStatus status = OrderStatus.SHIPPED;
if (status == OrderStatus.SHIPPED) {
System.out.println("Your order is on its way!");
}
Unlike a plain String, the compiler guarantees status can only ever be one of the four defined constants — there’s no risk of a typo like "SHIPED" slipping through unnoticed.
What’s next
Next: Record, a modern Java class type designed specifically for holding immutable data.