Java Enums
Enums in Java are a special type of class that represents a group of constants (unchangeable variables). They are used when you have a fixed set of values that are known at compile time, such as days of the week, directions, etc.
1. Defining Enums
Enums are defined using the enum
keyword.
public enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
2. Using Enums
You can use enums by referring to their constants.
public class EnumExample {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println("Today is " + today);
}
}
// Output: Today is MONDAY
3. Enum Methods
Enums have built-in methods like values()
and valueOf()
.
values()
: Returns an array of all enum constants.valueOf(String name)
: Returns the enum constant with the specified name.
for (Day day : Day.values()) {
System.out.println(day);
}
4. Adding Methods and Fields to Enums
Enums can have fields, methods, and constructors.
public enum Direction {
NORTH("Up"),
SOUTH("Down"),
EAST("Right"),
WEST("Left");
private String description;
private Direction(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public class EnumTest {
public static void main(String[] args) {
Direction dir = Direction.NORTH;
System.out.println(dir.getDescription()); // Outputs: Up
}
}
5. Key Takeaways
- Enums represent a fixed set of constants.
- Use the
enum
keyword to define enums. - Enums can have methods, fields, and constructors.
- They enhance code readability and safety by restricting values to predefined constants.
- Enums are inherently serializable and comparable.