Enums

Core Java · lesson 12 of 42 · 3 min read

Replace magic strings with a fixed, compiler-checked set of constants that can carry data.

Open this lesson in the learning hub

Key points

  • An enum is a fixed set of named constants. The compiler checks them, unlike String or int codes.
  • Enum constants can hold fields and methods, so each one carries its own data and behaviour.
  • Constants are singletons, so == is the right comparison. values() lists them all.
  • valueOf("HIGH") parses a name and throws IllegalArgumentException if it does not match, so guard user input.
  • Never persist ordinal(). Reordering the constants would silently change stored data — store name().
  • EnumMap and EnumSet are compact, fast, and iterate in declaration order.

Example

import java.util.EnumMap;

public class Main {

    enum Level {
        LOW(1, "green"),
        MEDIUM(5, "amber"),
        HIGH(10, "red");

        private final int weight;
        private final String colour;

        Level(int weight, String colour) {
            this.weight = weight;
            this.colour = colour;
        }

        int weight() { return weight; }

        String colour() { return colour; }

        boolean urgent() { return weight >= 5; }
    }

    public static void main(String[] args) {
        for (Level l : Level.values()) {
            System.out.println(l + " ordinal=" + l.ordinal() + " weight=" + l.weight()
                    + " colour=" + l.colour() + " urgent=" + l.urgent());
        }

        Level parsed = Level.valueOf("HIGH");
        System.out.println("valueOf(HIGH) == Level.HIGH : " + (parsed == Level.HIGH));

        EnumMap<Level, Integer> open = new EnumMap<>(Level.class);
        open.put(Level.HIGH, 2);
        open.put(Level.LOW, 7);
        System.out.println("EnumMap keeps declaration order: " + open);
    }
}

Enums turn magic strings into constants the compiler can check.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.