Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Enums

    ordinal() — position (0-based) — don't store it anywhere; reordering the constants changes it.

    Chapter 11 of 123 min read

    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.

    Java
    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;
        }
    }
    Java
    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";
    };
    // silver
    • ordinal() = 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 / EnumSet are 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 questions
    1

    Why use an enum instead of a String for grades?

    Show answer

    Only the defined values are possible, so typos are compile errors, and switches can be checked for completeness.

    2

    Can an enum have fields and methods?

    Show answer

    Yes — enums are full classes with private constructors.

    3

    Why shouldn't you save ordinal() values to a database?

    Show answer

    They change if constants are reordered or inserted, silently corrupting stored data. Store name() instead.