Enum

An enum (enumerated type) is a class whose instances are a fixed, named set of constants. Enums are type-safe: you cannot pass an arbitrary int where a specific enum value is expected.

Basic enum

public enum Status {
    ACTIVE, INACTIVE, PENDING, DELETED
}

Status s = Status.ACTIVE;
if (s == Status.PENDING) { ... }

Enum with fields and methods

public enum HttpMethod {
    GET(true, false),
    POST(false, true),
    PUT(false, true),
    DELETE(false, false);

    private final boolean safe;
    private final boolean hasBody;

    HttpMethod(boolean safe, boolean hasBody) {
        this.safe = safe;
        this.hasBody = hasBody;
    }

    public boolean isSafe()     { return safe; }
    public boolean hasBody()    { return hasBody; }
}

HttpMethod.POST.hasBody();  // true

Switch on enum

String message = switch (status) {
    case ACTIVE   -> "User is active";
    case INACTIVE -> "User is inactive";
    case PENDING  -> "User awaiting approval";
    case DELETED  -> "User has been removed";
};

EnumSet and EnumMap

Use EnumSet and EnumMap instead of HashSet / HashMap when keys are enum values — they are backed by bit vectors / small arrays and are dramatically faster.

Enums are classes

Enums can implement interfaces, have constructors, override methods. They cannot be instantiated with new or subclassed.