TExcelTAD
Home › Java › Java Enums

Java Enums

An enum (short for enumeration) is a special type that has a fixed set of named values — the days of the week, the suits in a card deck, the states of an order. Using an enum instead of plain strings or numbers means the compiler rejects invalid values and your IDE can autocomplete the valid ones.

Declaring an enum

java · try it yourself
enum Level {
    LOW, MEDIUM, HIGH
}

class Main {
    public static void main(String[] args) {
        Level current = Level.MEDIUM;
        System.out.println(current);
        System.out.println(current == Level.MEDIUM);
        System.out.println(current.name() + " has position " + current.ordinal());
    }
}
MEDIUM
true
MEDIUM has position 1

Enum constants are written in UPPER_CASE by convention. Each constant is a single object, so comparing with == is safe and idiomatic.

Enums in switch

Enums and switch are a perfect match. Inside the case labels you write the constant's name without the enum prefix:

java · try it yourself
enum TrafficLight {
    RED, YELLOW, GREEN
}

class Main {
    static String action(TrafficLight light) {
        return switch (light) {
            case RED -> "Stop";
            case YELLOW -> "Slow down";
            case GREEN -> "Go";
        };
    }

    public static void main(String[] args) {
        for (TrafficLight t : TrafficLight.values()) {
            System.out.println(t + ": " + action(t));
        }
    }
}
RED: Stop
YELLOW: Slow down
GREEN: Go

This switch expression needs no default: the compiler knows all three constants are covered. If you later add a BLINKING constant, the compiler will flag every switch that forgets it.

Built-in methods

Method Returns
values() an array of all constants, in declaration order
valueOf("NAME") the constant with that exact name (throws if none)
name() the constant's name as a String
ordinal() its 0-based position in the declaration
compareTo(other) ordering by declaration position
java · try it yourself
enum Size { SMALL, MEDIUM, LARGE, XL }

class Main {
    public static void main(String[] args) {
        Size s = Size.valueOf("LARGE");
        System.out.println(s + " is bigger than MEDIUM: " + (s.compareTo(Size.MEDIUM) > 0));
        System.out.println("Sizes available: " + Size.values().length);
        try {
            Size.valueOf("HUGE");
        } catch (IllegalArgumentException e) {
            System.out.println("No such size: HUGE");
        }
    }
}
LARGE is bigger than MEDIUM: true
Sizes available: 4
No such size: HUGE

Enums with fields, constructors and methods

An enum is a full class. Its constants can carry data passed to a (private) constructor, and it can have methods:

java · try it yourself
enum Planet {
    MERCURY(3.303e23, 2.4397e6),
    EARTH(5.976e24, 6.37814e6),
    JUPITER(1.9e27, 7.1492e7);

    private static final double G = 6.67300E-11;
    private final double mass;     // kg
    private final double radius;   // m

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
}

class Main {
    public static void main(String[] args) {
        double earthWeight = 70;
        double massKg = earthWeight / Planet.EARTH.surfaceGravity();
        for (Planet p : Planet.values()) {
            System.out.printf("Weight on %-8s %6.1f%n", p, massKg * p.surfaceGravity());
        }
    }
}
Weight on MERCURY    26.4
Weight on EARTH      70.0
Weight on JUPITER   177.1

Constants can even override methods individually, and enums can implement interfaces:

java · try it yourself
interface Operation {
    int apply(int a, int b);
}

enum BasicOp implements Operation {
    PLUS("+") {
        public int apply(int a, int b) { return a + b; }
    },
    TIMES("*") {
        public int apply(int a, int b) { return a * b; }
    };

    private final String symbol;

    BasicOp(String symbol) { this.symbol = symbol; }

    String symbol() { return symbol; }
}

class Main {
    public static void main(String[] args) {
        for (BasicOp op : BasicOp.values()) {
            System.out.println("6 " + op.symbol() + " 7 = " + op.apply(6, 7));
        }
    }
}
6 + 7 = 13
6 * 7 = 42

Tip: For maps and sets keyed by an enum, use EnumMap and EnumSet from java.util. They are extremely fast and keep entries in declaration order.

Test yourself

What does Day.values() return?

  1. The number of constants
  2. An array of all constants in declaration order
  3. A random constant
  4. A list of names as strings

Given enum Color { RED, GREEN, BLUE }, what is Color.BLUE.ordinal()?

  1. 0
  2. 1
  3. 2
  4. 3

Can an enum have fields and a constructor?

  1. No, only constants
  2. Yes, and the constructor is implicitly private
  3. Yes, but the constructor must be public
  4. Only static fields