Switch Expressions with Enums
Use modern switch expressions with enums for clean, exhaustive branching.
Switch Expressions with Enums
Switch expressions (Java 14+) with enums provide exhaustive, concise type-based routing. When all enum constants are covered, no default is needed.
Traditional Switch Statement
The classic switch statement works with enums but requires break to prevent fall-through.
enum Severity { LOW, MEDIUM, HIGH, CRITICAL }
Severity s = Severity.HIGH;
String action;
switch (s) {
case LOW:
action = "Log and monitor";
break;
case MEDIUM:
action = "Notify on-call team";
break;
case HIGH:
action = "Page engineer immediately";
break;
case CRITICAL:
action = "Activate incident response";
break;
default:
action = "Unknown";
}
System.out.println(action); // Page engineer immediatelyAll lessons in this course
- Defining and Using Enums
- Enums with Fields and Methods
- Switch Expressions with Enums
- EnumSet and EnumMap