Enums

An enum (short for "enumeration") is a special Java type that represents a fixed set of named constants. Instead of scattering loosely related values throughout your code, an enum groups them into one type-safe, self-documenting list.

Declaring and Using an Enum

Example: Days of the Week

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

public class EnumDemo {
  public static void main(String[] args) {
    Day today = Day.FRIDAY;
    System.out.println(today); // FRIDAY
  }
}

Enums in a switch Statement

Enums pair naturally with switch statements — the compiler already knows every possible value the enum can hold, which makes the code easy to read and safe to extend.

Day today = Day.FRIDAY;

switch (today) {
  case SATURDAY:
  case SUNDAY:
    System.out.println("It's the weekend!");
    break;
  default:
    System.out.println("It's a weekday.");
}
          

Enums with Fields and Constructors

Enums aren't limited to plain names — each constant can carry its own data. This is done by giving the enum fields and a constructor, just like a regular class. Every constant listed at the top then supplies the values for that constructor.

Example: Planets with Mass

enum Planet {
  MERCURY(3.3), VENUS(4.8), EARTH(5.9);

  private final double mass;

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

  public double getMass() {
    return this.mass;
  }
}

public class PlanetDemo {
  public static void main(String[] args) {
    System.out.println(Planet.EARTH.getMass()); // 5.9
  }
}

What's happening:

  • Each constant — MERCURY, VENUS, EARTH — supplies its own value to the enum's constructor, just like calling a constructor when creating an object.
  • The constructor of an enum is always implicitly private; you never write new Planet(...) yourself.
  • A getter like getMass() lets you read the field attached to each constant.

Why Enums Are Safer Than Plain Constants

Before enums existed, developers often used plain int or String constants to represent a fixed set of options — for example, int MONDAY = 0. The problem is that the compiler can't stop you from passing in 7, -1, or any other invalid int where a day was expected. With an enum, the compiler only allows the values that actually belong to that enum type, catching invalid values before the program ever runs.

Next up: learn how primitives get an object wrapper with Wrapper Classes.