EMZETT.
Login

Enum

In short: A data type consisting of a fixed, predefined set of named constants — e.g. the days of the week or the compass directions, for which only exactly these limited, known values can exist.

In more detail: Instead of using arbitrary numbers or strings to represent a limited state (e.g. 1 for Monday), an enum makes the valid values explicit and checkable by the compiler — an invalid value like 8 for a weekday simply isn’t possible at all. This makes code more readable and less error-prone than loose numeric or string constants.

In Depth

The contrast makes the advantage clear:

// WITHOUT enum: "magic numbers" with no context, typos go unnoticed
status = 2   // what does 2 mean? you have to look it up in the code
 
// WITH enum: self-explanatory, invalid values are impossible
status = Status.ACTIVE

With loose numbers or strings, ANY arbitrary value can be assigned — a typo ("active" instead of "active " with a trailing space) or a wrong number often only becomes noticeable at runtime, when a comparison unexpectedly fails. With an enum, the compiler already checks at compile time whether only one of the defined values is used — a typo is flagged immediately as an error, not just as mysterious runtime behaviour later.

enum Weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
 
Weekday today = Weekday.MONDAY;

Another important advantage shows up with the switch statement: many modern compilers can warn (or even throw an error) for a switch over an enum value if NOT ALL possible enum values are handled — if a new value is later added to the enum, the compiler automatically flags all spots in the code that don’t yet account for this new case. That would be impossible with loose string or number constants, because the compiler doesn’t know which values even count as “all possible” ones.

In many languages, enum values are internally not just simple constants, but full-fledged objects — in Java, an enum can even have its own fields and methods, so that, for example, every weekday can additionally store whether it’s a weekend day. This makes enums a more powerful tool than plain “named numbers”, even though the core use case — a fixed, closed set of valid states — stays the same.

See also: Non-primitive Types