An enum defines a fixed set of named constants. You can use it to represent values such as order statuses, directions, or days of the week.
In this example, you will define an enum for order statuses and use a switch expression to select a message.
Source code
Save the following code as EnumExample.java:
public class EnumExample {
void main() {
OrderStatus status = OrderStatus.SHIPPED;
String message = switch (status) {
case PENDING -> "Your order is waiting for confirmation.";
case PROCESSING -> "Your order is being prepared.";
case SHIPPED -> "Your order is on its way.";
case DELIVERED -> "Your order has arrived.";
};
IO.println("Current status: " + status);
IO.println("Message: " + message);
IO.println();
IO.println("Available statuses:");
for (OrderStatus availableStatus : OrderStatus.values()) {
IO.println(availableStatus);
}
}
}
enum OrderStatus {
PENDING,
PROCESSING,
SHIPPED,
DELIVERED
}
Explanation
The enum keyword declares a type with a fixed set of constants:
enum OrderStatus {
PENDING,
PROCESSING,
SHIPPED,
DELIVERED
}
Enum constant names conventionally use uppercase letters, with underscores separating words.
Assigning an enum value
Use the enum type followed by a constant name:
OrderStatus status = OrderStatus.SHIPPED;
The variable status can hold a reference to an OrderStatus constant. You cannot assign a string such as "SHIPPED" directly to it.
This helps prevent mistakes caused by spelling or capitalization differences in string values.
Using an enum in a switch expression
The switch expression selects a message for the current status:
String message = switch (status) {
case PENDING -> "Your order is waiting for confirmation.";
case PROCESSING -> "Your order is being prepared.";
case SHIPPED -> "Your order is on its way.";
case DELIVERED -> "Your order has arrived.";
};
Inside these case labels, you can use the constant names without the OrderStatus. prefix.
The expression covers every constant declared in OrderStatus, so a default rule is unnecessary.
Looping through enum constants
Every enum provides a values() method that returns an array of its constants in declaration order:
for (OrderStatus availableStatus : OrderStatus.values()) {
IO.println(availableStatus);
}
Here, the loop prints all four statuses, starting with PENDING.
Run the example
Compile and run the file:
javac EnumExample.java
java EnumExample
Output
Current status: SHIPPED
Message: Your order is on its way.
Available statuses:
PENDING
PROCESSING
SHIPPED
DELIVERED
Use an enum when a value should come from a known set of choices. It gives those choices meaningful names and lets the compiler check their usage.
