The Plain Picture#
A traffic light has exactly three states. Not four, not "purple". If you represent it with a string, someone will eventually write
"gren".
The Real Names#
An enum (enumeration) is a type with a fixed set of named instances. In Java, enums are full classes: they can have fields, constructors and methods.
enum Grade {
A(200, "Excellent"),
B(150, "Good"),
C(0, "Needs practice"); // the ONLY three Grade objects that will ever exist
final int minPoints;
final String message;
Grade(int minPoints, String message) {
// enum constructors are always private
this.minPoints = minPoints;
this.message = message;
}
static Grade of(int points) {
for (Grade g : values()) if (points >= g.minPoints) return g; // values() = all constants, in order
return C;
}
}System.out.println(
Grade.of(210) +
" " +
Grade.of(160).message +
" " +
Grade.of(40) +
" " +
Grade.B.ordinal() +
" " +
Grade.valueOf("A").minPoints +
" " +
Arrays.toString(Grade.values())
);
// A Good C 1 200 [A, B, C]
String badge = switch (Grade.of(170)) {
// switch over an enum: the compiler checks you covered every case
case A -> "gold";
case B -> "silver";
case C -> "keep going";
};
// silverordinal()= position (0-based) — don't store it anywhere; reordering the constants changes it.valueOf("A")= look up by name (throws if there's no such constant).Enums can be compared with
==safely — each constant is a single object.EnumMap/EnumSetare very fast collections keyed by enums (Collections, From the Inside).A single-constant enum is the simplest correct way to write a Singleton (one instance only) in Java (Creational Patterns (coming soon)).
Check yourself
3 questionsWhy use an enum instead of a String for grades?
Show answerHide answer
Only the defined values are possible, so typos are compile errors, and switches can be checked for completeness.
Can an enum have fields and methods?
Show answerHide answer
Yes — enums are full classes with private constructors.
Why shouldn't you save ordinal() values to a database?
Show answerHide answer
They change if constants are reordered or inserted, silently corrupting stored data. Store name() instead.