Enum
Sometimes a value can only be one of several predefined options: for example,
an order status, a priority level, or a process state.
For these cases, Java provides enum — a type with a fixed set of named values.
enum OrderStatus {
NEW,
PAID,
SHIPPED,
DELIVERED
}
Each name inside OrderStatus is a separate constant of that type.
Instead of strings such as "paid", the code now works with specific values
that the compiler can check.
OrderStatus status = OrderStatus.PAID;
if (status == OrderStatus.PAID) {
System.out.println("Payment received");
}
Constants of the same enum can be conveniently compared with ==:
each constant represents the single object for that value.
Working with enum values
An enum works naturally with switch.
Inside the branches, you only need the constant names without the enum type name.
String message = switch (status) {
case NEW -> "Created";
case PAID -> "Paid";
case SHIPPED -> "On the way";
case DELIVERED -> "Delivered";
};
When every constant is handled, this switch does not need a
default branch. This helps reveal changes: if a new value is later added to the
enum, places that fully handle the set will need to be updated.
You can get all constants through the automatically available values() method:
for (OrderStatus value : OrderStatus.values()) {
System.out.println(value);
}
The reverse operation is available too. valueOf() finds a constant by its exact name:
OrderStatus status = OrderStatus.valueOf("PAID");
valueOf() requires the exact constant name.
For example, "PAID" matches, while "paid" is a different string value.
An enum can store data and behavior
An enum is not just a list of strings.
Its constants are objects, so the type itself can have fields, a constructor, and methods.
This is useful when each option needs additional data associated with it.
enum Priority {
LOW(1),
MEDIUM(2),
HIGH(3);
private final int weight;
Priority(int weight) {
this.weight = weight;
}
int weight() {
return weight;
}
}
The number in parentheses is passed to the constructor of the corresponding constant.
Now the data can be obtained directly from the enum value:
int weight = Priority.HIGH.weight();
The semicolon after the list of constants is required when fields or methods are declared after them.
You cannot create an additional value with new Priority(...):
the set of instances is defined by the enum declaration itself.
enum when the set of options is truly fixed.
This way the code stores not an arbitrary string or number, but a value with a clear type and a predefined set of allowed options.