Skills101

AdvancedJava Programming · Lesson 18 of 29 · Updated ·

Enums in Java — Fixed Sets of Constants with Fields, Methods and switch

Many values in a program come from a small, fixed list: the days of the week, the status of an order (placed, shipped, delivered), the plans of a course (free, basic, pro). An enum (short for enumeration) is a special class whose objects are exactly that fixed list — no more, no less.

1. Why not just use int or String constants?

Before enums, programmers wrote constants like static final int PLACED = 0, SHIPPED = 1;. That has problems:

  • A method setStatus(int s) happily accepts setStatus(42) — the compiler cannot help.
  • Printing the status shows 1, not SHIPPED.
  • With Strings, a typo like "SHIPED" is only found at runtime, if ever.

An enum fixes all three:

enum Status { PLACED, SHIPPED, DELIVERED, CANCELLED }

public class Main {
    static String message(Status s) {
        return switch (s) {
            case PLACED -> "We got your order";
            case SHIPPED -> "On the way";
            case DELIVERED -> "Enjoy!";
            case CANCELLED -> "Refund started";
        };
    }

    public static void main(String[] args) {
        Status s = Status.SHIPPED;
        System.out.println(s + ": " + message(s));
        System.out.println(s == Status.SHIPPED);
        // message(1);  ← compile error: an int is not a Status
    }
}
SHIPPED: On the way
true
  • Status is a type. Only Status values can be passed where a Status is expected.
  • Printing an enum shows its name.
  • Enum constants are compared safely with ==, because each constant exists exactly once.
  • The arrow switch above has no default: because it covers every constant, the compiler knows it is complete.

2. Built-in methods

Every enum automatically gets these methods:

MethodGivesExample result
Status.values()array of all constants, in declared order[PLACED, SHIPPED, …]
Status.valueOf("SHIPPED")the constant with that exact nameSHIPPED
s.name()the name as a String"SHIPPED"
s.ordinal()position, starting at 01
a.compareTo(b)compares by ordinalnegative / 0 / positive
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }

public class Main {
    public static void main(String[] args) {
        for (Day d : Day.values()) {
            if (d.ordinal() >= 5) System.out.print(d + "(weekend) ");
        }
        System.out.println();
        Day d = Day.valueOf("WED");
        System.out.println(d.name() + " " + d.ordinal() + " " + d.compareTo(Day.FRI));
        try {
            Day.valueOf("wed");                   // names are case-sensitive
        } catch (IllegalArgumentException e) {
            System.out.println("No constant named wed");
        }
    }
}
SAT(weekend) SUN(weekend) 
WED 2 -2
No constant named wed

Do not store ordinal() in a database or file. If someone later adds a constant in the middle, every number after it shifts. Store name() instead.

3. Enums with fields, constructors and methods

An enum is a full class. Each constant is an object created once when the enum is loaded, and it can carry its own data.

Enum Plan has three constant objects, each created once: FREE with price 0 and 5 lessons, BASIC with price 499 and 50 lessons, PRO with price 1999 and unlimited lessons; Plan.PRO.price() reads 1999

enum Plan {
    FREE(0, 5), BASIC(499, 50), PRO(1999, Integer.MAX_VALUE);   // constants call the constructor

    private final int price;
    private final int lessons;

    Plan(int price, int lessons) {          // always private: nobody else can create a Plan
        this.price = price;
        this.lessons = lessons;
    }

    int price() { return price; }

    String lessonsText() {
        return lessons == Integer.MAX_VALUE ? "unlimited" : String.valueOf(lessons);
    }
}

public class Main {
    public static void main(String[] args) {
        for (Plan p : Plan.values()) {
            System.out.println(p + ": ₹" + p.price() + ", lessons " + p.lessonsText());
        }
        int total = Plan.BASIC.price() * 3;
        System.out.println("3 BASIC plans cost ₹" + total);
    }
}
FREE: ₹0, lessons 5
BASIC: ₹499, lessons 50
PRO: ₹1999, lessons unlimited
3 BASIC plans cost ₹1497

Rules:

  • The constants must come first, ending with ; if anything follows.
  • The constructor is always private (you may leave out the word). You can never write new Plan(…).
  • Fields are usually final: a plan's price should not change while the program runs.

A different method body for each constant

A constant can override a method. Here each operator knows how to apply itself:

enum Op {
    ADD("+") { int apply(int a, int b) { return a + b; } },
    SUB("-") { int apply(int a, int b) { return a - b; } },
    MUL("*") { int apply(int a, int b) { return a * b; } };

    final String symbol;
    Op(String symbol) { this.symbol = symbol; }
    abstract int apply(int a, int b);       // every constant must implement this
}

public class Main {
    public static void main(String[] args) {
        for (Op op : Op.values()) {
            System.out.println("12 " + op.symbol + " 4 = " + op.apply(12, 4));
        }
    }
}
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48

This avoids a long switch on the operator, and the compiler forces every new constant to supply apply.

4. EnumMap and EnumSet

When the keys of a map are enum constants, use EnumMap. Inside, it is just an array indexed by ordinal(), so it is fast and keeps keys in declared order. EnumSet is a set of constants stored as bits.

EnumMap stores values in an array indexed by each constant's ordinal: PLACED at 0, SHIPPED at 1, DELIVERED at 2, CANCELLED at 3, so the map keeps declared order

import java.util.*;

enum Status { PLACED, SHIPPED, DELIVERED, CANCELLED }

public class Main {
    public static void main(String[] args) {
        List<Status> orders = List.of(Status.SHIPPED, Status.PLACED, Status.SHIPPED,
                                      Status.DELIVERED, Status.SHIPPED, Status.CANCELLED);
        Map<Status, Integer> count = new EnumMap<>(Status.class);
        for (Status s : orders) count.merge(s, 1, Integer::sum);
        System.out.println(count);

        Set<Status> open = EnumSet.of(Status.PLACED, Status.SHIPPED);
        Set<Status> closed = EnumSet.complementOf(EnumSet.copyOf(open));
        System.out.println(open + " " + closed);
    }
}
{PLACED=1, SHIPPED=3, DELIVERED=1, CANCELLED=1}
[PLACED, SHIPPED] [DELIVERED, CANCELLED]

5. More facts interviewers ask

  • Every enum secretly extends java.lang.Enum, so an enum cannot extend another class. It can implement interfaces.
  • Enum constants are created once by the JVM, so an enum with one constant is the simplest thread-safe Singleton: enum Config { INSTANCE; }.
  • Enums can be used in switch, as HashMap keys, and in sets — equals and hashCode already work.
  • You cannot create enum objects with new or by reflection.

Common mistakes

  • Using int or String constants where an enum gives type safety for free.
  • Saving ordinal() to a database; adding a constant later breaks old data.
  • Calling valueOf with user input without catching IllegalArgumentException (wrong case, extra spaces).
  • Forgetting the ; after the constants when the enum has fields or methods.
  • Using HashMap<Status, …> where EnumMap is simpler and faster.

Quick recap

  • An enum is a class with a fixed set of objects: enum Status { PLACED, SHIPPED }.
  • values(), valueOf(), name(), ordinal(); compare constants with ==.
  • Enums can have final fields, a private constructor, methods and constant-specific bodies.
  • EnumMap and EnumSet are the fast collections for enum keys and values.
  • Enums extend Enum, can implement interfaces, and make a simple Singleton.

Practice what you learned

📝 Quiz: Java Enums5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →