Enums in Switch Statements
One of the best places to use an Enum is inside a switch statement.
Because the compiler knows exactly what all the possible values of an enum are, using them in switch statements makes your code incredibly clean, readable, and perfectly type-safe.
Example: Switch Case with Enums
When you pass an enum variable into a switch statement, you do not need to prefix the case labels with the enum type name. You just use the constant name directly (e.g., MONDAY, not Day.MONDAY).
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
}
public class LabEnumSwitch1 {
public static void main(String[] args) {
Day today = Day.FRIDAY;
// Passing the enum directly into the switch statement
switch (today) {
case MONDAY:
System.out.println("Start of the work week.");
break;
case FRIDAY:
System.out.println("TGIF! Almost the weekend.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend! Relax.");
break;
default:
System.out.println("Just another mid-week day.");
break;
}
}
}
Output:
TGIF! Almost the weekend.
Why is this better than integers?
If we had used integers (public static final int MONDAY = 1), our switch statement would look like this:
int today = 5;
switch (today) {
case 1: ...
case 5: ...
}
This is known as using "Magic Numbers". It is very hard to read because the number 5 has no inherent meaning to a developer reading the code. The compiler also can't stop you from doing case 99:, which is an invalid day.
By using an Enum in the switch statement:
- The code documents itself (you read
case FRIDAY:). - The compiler guarantees that you can only switch on valid
Dayconstants.