Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

enum

Declares an enum — a type with a fixed set of values.

Available since: Java 5

Syntax

enum Name { A, B, C }

Examples

An enum and a switch over it:

enum Size { SMALL, MEDIUM, LARGE }
 
void main() {
    Size size = Size.MEDIUM;
    String label = switch (size) {
        case SMALL -> "S";
        case MEDIUM -> "M";
        case LARGE -> "L";
    };
    IO.println(size + " " + label);
    IO.println(Arrays.toString(Size.values()));
}

Output:

MEDIUM M
[SMALL, MEDIUM, LARGE]

Fields, a constructor and methods in an enum:

enum Coin {
    PENNY(1), NICKEL(5), DIME(10);
 
    private final int cents;
 
    Coin(int cents) {
        this.cents = cents;
    }
 
    int cents() {
        return cents;
    }
}
 
void main() {
    IO.println(Coin.DIME.cents());
    IO.println(Coin.valueOf("NICKEL").ordinal());
    IO.println(Coin.PENNY.name());
}

Output:

10
1
PENNY

Notes

values() returns all values in order, valueOf("NAME") finds a value by name (an unknown name throws IllegalArgumentException), ordinal() is the zero-based position. Compare enum values with ==. For sets and maps keyed by an enum there are the fast EnumSet and EnumMap.

See also

  • switch — Picks a branch by value; as an expression it returns a result.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
  • sealed / permits — Restricts which classes may extend a class or implement an interface.

Related recipes

In the tutorial

  • Enums — Enums in Java: a fixed set of values, values() and valueOf(), switch over an enum, fields and methods.

Thanks for reading!

Donate to the site — we work hard for you.