What is an Enum in Java?
In Java, an enum is a special data type that represents a collection of constants. Each constant in an enum is an instance of the enum type, making it type-safe and more readable. Enums are used when you have a fixed set of predefined values, such as days of the week, months or directions.
Key Features of Enums in Java
- Type-Safe Constants: Enums provide a type-safe way to define a fixed set of constants.
- Implicitly Static and Final: Enum constants are static and final, ensuring immutability.
- Methods and Fields: Enums can have methods, fields, and constructors.
- Implements Interfaces: Enums can implement interfaces to provide additional functionality.
- Switch Statement Compatibility: Enums can be used in switch statements for cleaner code.
Syntax of Enum
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
Example: Enum Declaration
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
How to Use Enums in Java
Access Enum Values
You can access enum constants using their name:
public class Main {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println("Today is: " + today);
}
}
Output:
Today is: MONDAY
Enum in Switch Statements
Enums work seamlessly with switch statements, simplifying conditional logic.
Example: Enum in a Switch Statement
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class Main {
public static void main(String[] args) {
Day today = Day.FRIDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the work week.");
break;
case FRIDAY:
System.out.println("Weekend is near!");
break;
case SUNDAY:
System.out.println("Relax, it's Sunday!");
break;
default:
System.out.println("It's a weekday.");
}
}
}
Output:
Weekend is near!
Adding Methods to Enums
Enums can have methods to provide additional functionality.
Example: Enum with a Method
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
public class Main {
public static void main(String[] args) {
Day today = Day.SATURDAY;
System.out.println("Is it weekend? " + today.isWeekend());
}
}
Output:
Is it weekend? true
Enum with Constructors, Fields and Methods
Enums can have private fields, constructors, and methods to associate additional information with each constant.
Example: Enum with Additional Fields
enum Season {
SPRING("Warm"),
SUMMER("Hot"),
FALL("Cool"),
WINTER("Cold");
private String description;
// Constructor
private Season(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public class Main {
public static void main(String[] args) {
for (Season season : Season.values()) {
System.out.println(season + ": " + season.getDescription());
}
}
}
Output:
SPRING: Warm
SUMMER: Hot
FALL: Cool
WINTER: Cold
Enum Methods
- values(): Returns an array of all enum constants.
- ordinal(): Returns the position (index) of an enum constant.
- valueOf(String name): Returns the enum constant with the specified name.
Example: Using Enum Methods
enum Color {
RED, GREEN, BLUE;
}
public class Main {
public static void main(String[] args) {
// values() method
for (Color color : Color.values()) {
System.out.println(color);
}
// ordinal() method
Color selectedColor = Color.GREEN;
System.out.println("Index of GREEN: " + selectedColor.ordinal());
// valueOf() method
Color colorFromString = Color.valueOf("RED");
System.out.println("Color from string: " + colorFromString);
}
}
Output:
RED
GREEN
BLUE
Index of GREEN: 1
Color from string: RED
When to Use Enums?
- Predefined Constants: Use enums for fixed values like days, months or directions.
- Switch Statements: Enums make switch statements more readable and manageable.
- Type Safety: Enums enforce type safety, reducing errors caused by invalid constants.
Advantages of Enums
- Improves Code Readability: Enums make code more self-explanatory.
- Enhances Type Safety: Prevents invalid values from being used.
- Simplifies Code Maintenance: Centralizes constant values in one place.
- Supports Advanced Features: Allows methods, fields and constructors for extended functionality.