Middle+
What are enums used for in Java?
sobes.tech AI
Answer from AI
An enum in Java is used to define a set of fixed constants that are logically related. It is a data type that restricts the possible values of a variable to a specific set.
Advantages of enum:
- They improve code readability and safety, as you cannot assign a value outside the defined set.
- They allow grouping related constants in one place.
- They can contain methods and fields, making them more functional than just a set of constants.
Example of using enum:
public enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
// Usage:
DayOfWeek today = DayOfWeek.MONDAY;
if (today == DayOfWeek.SATURDAY || today == DayOfWeek.SUNDAY) {
System.out.println("Weekend");
} else {
System.out.println("Workday");
}
Thus, enum helps avoid errors related to using strings or numbers to represent a limited set of values.