Enums
What are Enums?
Section titled “What are 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.
Basic Usage
Section titled “Basic Usage”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);}Built-in Methods
Section titled “Built-in Methods”| Method | Returns | Notes |
|---|---|---|
values() | Day[] | Array of all constants in declaration order |
valueOf("MONDAY") | Day | Parse from exact name; throws IllegalArgumentException if invalid |
name() | String | Exact declared name (e.g., "MONDAY") |
ordinal() | int | 0-based position in declaration order |
compareTo(other) | int | Compares by ordinal |
// ❌ "stringly typed" — any int compilespublic static final int STATUS_OK = 0;public static final int STATUS_ERR = 1;void handle(int status) {} // handle(42) compiles — oops
// ✅ type safeenum Status { OK, ERROR }void handle(Status s) {} // handle(42) won't compileEnum with Fields and Methods
Section titled “Enum with Fields and Methods”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 → GoEnum in Switch Statements
Section titled “Enum in Switch Statements”enum Direction { NORTH, SOUTH, EAST, WEST }
// Classic switchswitch (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 Singleton (Effective Java)
Section titled “Enum Singleton (Effective Java)”enum DatabaseConnection { INSTANCE;
private Connection conn;
DatabaseConnection() { conn = DriverManager.getConnection("jdbc:...", "user", "pass"); }
public Connection getConnection() { return conn; }}
// UsageConnection c = DatabaseConnection.INSTANCE.getConnection();| Approach | Serialization-safe | Reflection-safe | Lazy | Thread-safe |
|---|---|---|---|---|
Eager static final | No (needs readResolve) | No | No | Yes |
| Double-checked locking | Needs care | No | Yes | Yes |
| Holder pattern | Needs care | No | Yes | Yes |
| Enum singleton | Yes | Yes | No | Yes |