Skip to content

Enums — cheat sheet

From: fundamentals/13-enums.md.

  • What: a fixed, predetermined set of values, defined as its own type (enum Direction { NORTH, EAST, SOUTH, WEST }) — usable anywhere any other type is.
  • Why not just Strings/ints for this: those allow any value, not just the intended handful — nothing stops a typo'd string or an out-of-range number from compiling.
  • The core benefit — type safety: comparing/switching on enum constants means the compiler rejects references to values that don't exist. Concretely: if a diagonal direction (NORTH_EAST, etc.) is later removed from the enum because it's no longer supported, every leftover case Direction.NORTH_EAST or direction == Direction.NORTH_EAST in the codebase fails to compile — turning a silent dead-code bug (which happens with plain String/.equals() checks, where old branches just quietly stop being reached) into a compiler error that forces cleanup.
  • Comparison: use == between enum constants (safe, since each constant is a singleton instance) rather than .equals().
  • Fields on an enum: an enum constant can carry its own data via a constructor, just like a regular class — e.g. a Direction enum storing a human-readable name field, with toString() overridden to return it.
  • switch on enums: works like switch on String/int (case VALUE: per constant, break, default), but gets the same type-safety guarantee as ==.