🎨
OOP

Enums

A Fixed Set of Choices
💡 An enum is like a traffic signal — only RED, YELLOW, GREEN exist, there's no possible 4th color. Fixed, predefined choices.

An enum is a special type where only fixed constants are defined — like Day.MONDAY, Day.TUESDAY.

It's better than a plain String/int because the compiler won't let an invalid value slip through — only the options you defined are allowed.

enum Level { LOW, MEDIUM, HIGH }

Level l = Level.MEDIUM;
if (l == Level.MEDIUM) System.out.println("Medium level!");
🎨
An enum is like a traffic signal — only RED, YELLOW, GREEN exist, there's no possible 4th color. Fixed, predefined choices.
1 / 6
⚡ Quick Recap
  • A fixed set of named constants
  • Type-safe — no invalid values allowed
  • Like a traffic signal: only predefined options
On this page (4 subtopics)

An enum isn't limited to simple constants — every constant can have its own fields and constructor too. The constructor is always private (implicitly), since enum constants are only ever created at declaration, never with "new" from outside.

Classic example: a Planet enum where every planet has its mass and radius stored, plus a method to calculate gravity.

enum Planet {
  MERCURY(3.3e23, 2.4e6), EARTH(5.9e24, 6.4e6);
  final double mass, radius;
  Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
}

values() gives an array of all constants (useful for looping). ordinal() gives a constant's position (from 0) in declaration order — but relying on this is risky if the order changes in the future, so use it carefully. name() gives the constant's exact name as a String. valueOf("RED") builds an enum constant from a String (throws an exception if the name doesn't match).

for (Level l : Level.values()) {
  System.out.println(l.name() + " = " + l.ordinal());
}

Using an enum in a switch statement stays very clean — you don't need the enum's prefix (Level.) when writing a case, and since all possible values are fixed, the code stays safe (modern IDEs can even warn you if a case is missing).

Java provides special-purpose collections for enums: EnumMap (enum as the key, faster and more memory-efficient than HashMap since it's array-based internally) and EnumSet (a Set of enum constants, implemented internally with a bit-vector, very fast operations). Whenever keys/elements are enums, these are a better choice than a normal HashMap/HashSet.