Careeroza
Enum Basics
A Fixed Set of Constants
An enum is a special class with a fixed list of instances. Use it whenever a value can only be one of a known set: order status, day of week, payment mode, user role.
Example
public class Main {
enum OrderStatus { PLACED, PACKED, SHIPPED, DELIVERED, CANCELLED }
public static void main(String[] args) {
OrderStatus s = OrderStatus.SHIPPED;
System.out.println("Status: " + s);
System.out.println("name(): " + s.name() + ", ordinal(): " + s.ordinal());
System.out.println("== works: " + (s == OrderStatus.SHIPPED));
for (OrderStatus st : OrderStatus.values()) {
System.out.print(st + " ");
}
System.out.println();
OrderStatus parsed = OrderStatus.valueOf("DELIVERED");
System.out.println("Parsed: " + parsed);
System.out.println("Shipped before delivered? " + (OrderStatus.SHIPPED.compareTo(OrderStatus.DELIVERED) < 0));
}
}Output
Status: SHIPPED name(): SHIPPED, ordinal(): 2 == works: true PLACED PACKED SHIPPED DELIVERED CANCELLED Parsed: DELIVERED Shipped before delivered? true
Why Not String or int Constants?
String/int constants | enum | |
|---|---|---|
| Type safety | any string/int accepted | only valid constants compile |
| Typos | "SHIPED" compiles | SHIPED is a compile error |
| Extra data | separate maps | fields and methods on the enum |
| switch support | yes | yes, with exhaustiveness checks in switch expressions |
Note: valueOf("shipped") (wrong case) throws IllegalArgumentException. Normalise input with toUpperCase() first.