Codectionary / Developer documentation / Java

Enums

An enum (enumeration) is a special Java type used to define a fixed set of named constants, like the days of the week or possible states of an order. Enums are type-safe - the compiler ensures only valid enum values can be assigned - and, unlike simple constants, they are full classes that can have fields, constructors, and methods of their own.

Syntax

enum EnumName {\n  CONSTANT_1, CONSTANT_2\n}

Examples

Basic Enum

Defining and using a simple set of named constants.

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class EnumExample {
    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;

        if (today == Day.SATURDAY || today == Day.SUNDAY) {
            System.out.println("Weekend!");
        } else {
            System.out.println("Weekday");
        }
    }
}

Enum with switch

Enums integrate naturally with switch statements.

enum TrafficLight { RED, YELLOW, GREEN }

public static String getAction(TrafficLight light) {
    switch (light) {
        case RED:
            return "Stop";
        case YELLOW:
            return "Slow down";
        case GREEN:
            return "Go";
        default:
            return "Unknown";
    }
}

System.out.println(getAction(TrafficLight.GREEN));  // Go

Enum with Fields and Constructors

Enums can carry their own data, since each constant is actually an object.

public enum Planet {
    MERCURY(3.3e23, 2.4e6),
    EARTH(5.97e24, 6.4e6),
    MARS(6.4e23, 3.4e6);

    private final double mass;   // kg
    private final double radius; // meters

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

    public double surfaceGravity() {
        final double G = 6.67300E-11;
        return G * mass / (radius * radius);
    }
}

System.out.printf("Earth gravity: %.2f%n", Planet.EARTH.surfaceGravity());

Useful Enum Methods

Built-in methods every enum automatically gets: values(), name(), and ordinal().

enum Size { SMALL, MEDIUM, LARGE }

for (Size s : Size.values()) {  // iterate over every constant
    System.out.println(s.name() + " = " + s.ordinal());
}
// SMALL = 0
// MEDIUM = 1
// LARGE = 2

Size chosen = Size.valueOf("MEDIUM");  // parse from a String
System.out.println(chosen);

Best practices

  • Use enums instead of plain int or String constants whenever a variable should only take one of a fixed, known set of values - it gives you compile-time safety
  • Take advantage of switch statements with enums for exhaustive, readable branching on the possible values
  • Add fields and methods to an enum when each constant needs associated data, rather than maintaining a separate lookup table
  • Use ALL_CAPS naming for enum constants, following the same convention as other constants in Java

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading