Using Enums in switch Statements
What you'll learn: How to use enum constants directly in switch cases without repeatedly typing the enum class name.
When you use an enum in a switch statement, Java already knows the enum type from the variable you're switching on. This means you don't need to prefix each case with the enum class name—you just use the constant names directly.
The Core Idea
Think of it like checking into a hotel where you've already shown your ID at the front desk. You don't need to show it again at the elevator, the pool, or the gym—they already know who you are. Similarly, once you declare the enum variable in the switch expression, Java knows which enum type you're working with, so you can use the constant names by themselves in each case.
Syntax Example
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumSwitchDemo {
public static void main(String[] args) {
Day today = Day.WEDNESDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the work week");
break;
case FRIDAY:
System.out.println("Almost weekend!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekend time!");
break;
default:
System.out.println("Midweek day");
}
}
}
Notice how inside the switch, we write case MONDAY, not case Day.MONDAY. The enum type is already established by switch (today), where today is declared as type Day.
This makes switch statements with enums cleaner and more readable—no repetitive class prefixes cluttering your cases.
Key Takeaway: When using enums in switch statements, omit the enum class name in each case—Java infers it from the switch variable's type, keeping your code concise and clean.