Java › Enums
What is an enum in Java, and how does it differ from simply using a set of integer or String constants?
BeginnerAnswer
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 valueReal-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.