An enum (short for enumeration) is a special Java data type used to define collections of constants. Instead of using plain integers or strings to represent options, enums restrict variables to one of a few predefined values, making your code highly readable and type-safe.
In this guide, we will look at how to declare enums (both inside and outside a class) and how to evaluate them using switch cases.
Imagine a microwave or a dryer with a cycle selector knob:
- You can turn the knob to **WINTER**, **SPRING**, **SUMMER**, or **FALL**.
- You cannot turn the knob to a custom value like "Banana" or 5.6.
- The system is physically locked into those few preset choices. This is what an **enum** does for your variables.
1. Declaring Enums Outside vs. Inside Classes
You can declare enums either as standalone files/outer structures, or nested inside class declarations:
enum Season {
WINTER, SPRING, SUMMER, FALL
}
class EnumOutsideClass {
public static void main(String[] args) {
Season s = Season.WINTER;
System.out.println(s);
}
}
Enums declared outside can be shared globally across all classes in the package.
class EnumInClass {
enum Season {
WINTER, SPRING, SUMMER, FALL; // semicolon is optional for simple lists
}
public static void main(String[] args) {
Season s = Season.WINTER;
System.out.println(s);
}
}
Enums declared inside are scoped strictly to the enclosing class, preventing naming collisions in large packages.
2. Evaluating Enums with Switch Cases
Enums are a natural match for switch statements. Because the compiler knows all possible enum values, switch evaluations are extremely clean and readable:
class Enum_Switch {
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public static void main(String args[]) {
Day day = Day.MONDAY;
switch (day) {
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday"); // Prints!
break;
default:
System.out.println("other day");
}
}
}
Notice that inside the case statements, you don't write Day.SUNDAY—you simply write the constant name (SUNDAY) because Java infers the type from the switch parameter.
Conclusion
Use simple enums whenever you need to represent a fixed set of options. They make code self-documenting and prevent bugs caused by invalid user inputs or spelling mistakes in String constants.