Switch Expressions with Enums (Java 14+)
What you'll learn: How to use modern switch expressions with enums using arrow syntax and guaranteed completeness checking.
The Modern Switch Expression
Starting in Java 14, you can use switch expressions with enums. Unlike traditional switch statements (which execute code and use break), switch expressions return a value directly using arrow syntax (->). This makes your code cleaner and safer.
The key advantages:
1. Arrow Syntax: No need for break statements—each case is isolated automatically.
2. Return Values: The entire switch becomes an expression that evaluates to a value.
3. Exhaustiveness Checking: The compiler forces you to handle all enum constants (or provide a default). No missing cases!
Basic Syntax
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day day = Day.MONDAY;
String message = switch (day) {
case MONDAY -> "Start of work week";
case TUESDAY -> "Second day";
case WEDNESDAY -> "Midweek";
};
Notice: no break, no accidental fall-through, and the result is assigned directly to message.
Exhaustiveness in Action
If you forget a case, the compiler errors:
// This WON'T compile - missing WEDNESDAY!
String type = switch (day) {
case MONDAY -> "Bad";
case TUESDAY -> "Okay";
// Compiler error: switch expression does not cover all possible values
};
You must handle all constants or add a default case.
Multi-Line Cases
For complex logic, use a block with yield:
String result = switch (day) {
case MONDAY -> {
String temp = "Busy day";
yield temp.toUpperCase();
}
case TUESDAY, WEDNESDAY -> "Regular day";
};
Key Takeaway: Switch expressions with enums provide concise, type-safe code with automatic exhaustiveness checking—the compiler ensures you never miss a case, making your enum handling bulletproof.