The <code>enum</code> Keyword in Java
An enum is a class with a fixed, finite set of instances. Use one whenever a value must be one of a known set β days of the week, order statuses, HTTP methods, currencies. An enum is type-safe (you can't pass "foo" where an enum is expected) and far more expressive than static final constants.
Basic
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Day d = Day.MONDAY;
d.name(); // "MONDAY"
d.ordinal(); // 0 β don't use ordinal for business logic
With fields and methods
public enum Priority {
LOW(1), MEDIUM(5), HIGH(10);
private final int weight;
Priority(int weight) { this.weight = weight; }
public int weight() { return weight; }
}
Priority.HIGH.weight(); // 10
Per-constant behaviour
public enum Operation {
PLUS { public int apply(int a, int b) { return a + b; } },
MINUS { public int apply(int a, int b) { return a - b; } };
public abstract int apply(int a, int b);
}
Operation.PLUS.apply(3, 4); // 7
Iteration, lookup, conversion
for (Day d : Day.values()) System.out.println(d);
Day.valueOf("MONDAY"); // by name β throws IllegalArgumentException if unknown
// Robust lookup
Optional<Day> d = Arrays.stream(Day.values())
.filter(x -> x.name().equalsIgnoreCase("monday"))
.findFirst();
EnumSet and EnumMap
var weekdays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
var weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
var all = EnumSet.allOf(Day.class);
var schedule = new EnumMap<Day, List<Task>>(Day.class);
EnumSet is a bitmap internally β blazingly fast and memory-efficient. Use it for any "set of enum values" instead of Set<Day>.
Singleton via enum
public enum Config {
INSTANCE;
private final Properties props = load();
public Properties props() { return props; }
}
Config.INSTANCE.props();
switch on enum
String kind = switch (day) {
case SATURDAY, SUNDAY -> "Weekend";
default -> "Weekday";
};
Common mistakes
- Using
ordinal()in business logic β adding a constant in the middle silently renumbers others. Use an explicit field. - Storing ordinals in a database β same problem. Store the
name(). - Too many constants β if the "enum" is really a lookup table that grows, use a regular class backed by a
Map. - Non-exhaustive
switchβ add adefaultor handle every case; Java's exhaustiveness check is strict in switch expressions.
Related
Pillar: Java keywords. See also switch, sealed classes.