All 15 Enums questions
More in Enums
Advertisement
Back to results for “OOP & Classes”
Java › Enums

What is an enum in Java, and how does it differ from simply using a set of integer or String constants?

Beginner

Answer

An enum defines a fixed, type-safe set of named constants, where each constant is actually a full singleton instance of the enum type itself -- unlike int or String constants (which provide no compile-time type safety, allowing any arbitrary int/String value to be passed where a specific constant was intended), an enum's type system prevents passing an invalid value at all, since only the declared enum constants can exist as values of that type, catching a whole class of "invalid magic value" bugs at compile time rather than at runtime.
public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public void scheduleTask(Day day) { ... }

scheduleTask(Day.MONDAY);  // type-safe, only a valid Day constant can be passed
// scheduleTask(1);  // wouldn't even compile -- contrast with an int-constant-based approach
// where scheduleTask(99) would compile fine despite being a meaningless, invalid value
Real-world example A legacy codebase using int constants (STATUS_PENDING = 0, STATUS_APPROVED = 1) for an order's status is refactored to use an OrderStatus enum, immediately eliminating an entire class of bugs where an invalid or out-of-range integer could previously be silently passed and stored without any compile-time or even runtime detection.

Common follow-ups: Why can't you create a new instance of an enum type using 'new' the way you can with a regular class?;How does the compiler guarantee that only the declared enum constants can ever exist as values of that type?