Skip to content
Dev Dump

Enums

Under the hood, what you write:

enum Day { MON, TUE }

compiles to something like:

public final class Day extends Enum<Day> {
public static final Day MON = new Day("MON", 0);
public static final Day TUE = new Day("TUE", 1);
private static final Day[] VALUES = { MON, TUE };
public static Day[] values() { return VALUES.clone(); }
public static Day valueOf(String name) { /* lookup */ }
}

This is why enums can’t extend other classes (they already extend java.lang.Enum), but can implement interfaces.


enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.FRIDAY;
if (today == Day.FRIDAY) { // == is safe for enums
System.out.println("Weekend is coming!");
}
for (Day d : Day.values()) { // iterate all constants
System.out.println(d);
}
MethodReturnsNotes
values()Day[]Array of all constants in declaration order
valueOf("MONDAY")DayParse from exact name; throws IllegalArgumentException if invalid
name()StringExact declared name (e.g., "MONDAY")
ordinal()int0-based position in declaration order
compareTo(other)intCompares by ordinal

// ❌ "stringly typed" — any int compiles
public static final int STATUS_OK = 0;
public static final int STATUS_ERR = 1;
void handle(int status) {} // handle(42) compiles — oops
// ✅ type safe
enum Status { OK, ERROR }
void handle(Status s) {} // handle(42) won't compile

Enums can have fields, constructors, and methods — making them far more powerful than simple constant lists.

enum TrafficSignal {
RED("Stop"), YELLOW("Get Ready"), GREEN("Go");
private final String action; // fields should be final
TrafficSignal(String action) { // constructor is implicitly private
this.action = action;
}
public String getAction() { return action; }
}
for (TrafficSignal s : TrafficSignal.values()) {
System.out.println(s + "" + s.getAction());
}
// RED → Stop, YELLOW → Get Ready, GREEN → Go

enum Direction { NORTH, SOUTH, EAST, WEST }
// Classic switch
switch (dir) {
case NORTH: System.out.println("Up"); break;
case SOUTH: System.out.println("Down"); break;
case EAST: System.out.println("Right"); break;
case WEST: System.out.println("Left"); break;
}
// Java 14+ switch expression (exhaustive — compiler checks all cases)
String label = switch (dir) {
case NORTH -> "Up";
case SOUTH -> "Down";
case EAST -> "Right";
case WEST -> "Left";
};
enum DatabaseConnection {
INSTANCE;
private Connection conn;
DatabaseConnection() {
conn = DriverManager.getConnection("jdbc:...", "user", "pass");
}
public Connection getConnection() { return conn; }
}
// Usage
Connection c = DatabaseConnection.INSTANCE.getConnection();
ApproachSerialization-safeReflection-safeLazyThread-safe
Eager static finalNo (needs readResolve)NoNoYes
Double-checked lockingNeeds careNoYesYes
Holder patternNeeds careNoYesYes
Enum singletonYesYesNoYes