Junior — Middle
In what situations and for what purposes is enumeration used in programming?
sobes.tech AI
Answer from AI
Enums are used to define a limited set of constants that are logically related. This is convenient when working with a fixed set of values, such as days of the week, order statuses, or user types.
Using enums improves code readability and safety, as it eliminates the possibility of using incorrect values. Additionally, in Java, enums can contain methods and fields, which allows extending their functionality.
Example:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// Usage
Day today = Day.MONDAY;
if (today == Day.SATURDAY || today == Day.SUNDAY) {
System.out.println("Weekend");
} else {
System.out.println("Weekday");
}