Enums
TL;DR
- An Enum (Enumeration) is a special Java type used to define collections of constants (e.g., Days of the week, HTTP Status codes).
- Under the hood, an Enum is actually a fully-fledged Class.
- Enums provide type safety, exhaustive
switchstatement support, and built-in methods likevalues()andvalueOf().
Concept
Before Java 5, developers used “Int Constants” or “String Constants” to represent fixed categories:
public static final int STATUS_PENDING = 1;
The problem was there was zero type safety. You could pass the number 99 into a setStatus(int) method, and the compiler wouldn’t care, causing a runtime crash.
Enums solve this by strictly restricting the possible values to a predefined list. If a method takes a Status, you must pass a valid Status enum.
Examples
public enum CoffeeSize {
// These are actually public static final instances of CoffeeSize!
SMALL(150),
MEDIUM(250),
LARGE(400);
// Enums can have fields, constructors, and methods
private final int milliliters;
// The constructor is implicitly PRIVATE. You cannot call 'new CoffeeSize()'.
CoffeeSize(int milliliters) {
this.milliliters = milliliters;
}
public int getMilliliters() {
return milliliters;
}
}
public class EnumDemo {
public static void main(String[] args) {
CoffeeSize mySize = CoffeeSize.MEDIUM;
System.out.println("Size: " + mySize.getMilliliters() + "ml");
// Built-in iteration
for (CoffeeSize size : CoffeeSize.values()) {
System.out.println(size);
}
}
}
Interview Questions
Q: Can an Enum extend another class?
A: No. Every enum implicitly extends java.lang.Enum. Since Java doesn’t support multiple inheritance, an enum cannot extend any other class. However, it can implement multiple interfaces!
Q: What is the difference between name() and toString() on an enum?
A: - name() is a final method defined in java.lang.Enum. It returns the exact string literal used to declare the enum constant (e.g., "MEDIUM"). It cannot be overridden.
toString()also returns the name by default, but it is not final. You can override it to return a more user-friendly string (e.g.,"Medium (250ml)"). You should always usename()for serialization/database storage, andtoString()for UI display.