All 15 Enums questions
More in Enums
Advertisement
Java › Enums

How do you correctly use an enum as a switch statement/expression's target, and what changed with the introduction of arrow-style switch expressions (Java 14+) regarding exhaustiveness and fall-through?

Intermediate

Answer

Traditional colon-style switch statements over an enum use unqualified constant names in each case label (not Day.MONDAY, just MONDAY) and are prone to accidental fall-through if a break is forgotten; the newer arrow-style switch expressions (case X -> ...) eliminate fall-through entirely (each branch is independent, no accidental cascade into the next case), can directly return a value as an expression, and when covering every enum constant without a default branch, give the compiler the ability to verify exhaustiveness at compile time, immediately flagging if a new constant is later added without a corresponding case being handled.
enum Size { SMALL, MEDIUM, LARGE }

// Old style: fall-through risk if break is forgotten
switch (size) {
    case SMALL: System.out.println("S"); break;
    case MEDIUM: System.out.println("M"); break;
    case LARGE: System.out.println("L"); break;
}

// Modern arrow style: no fall-through risk, can be an expression, exhaustiveness-checkable
String label = switch (size) {
    case SMALL -> "S";
    case MEDIUM -> "M";
    case LARGE -> "L";
};
Real-world example A refactor from an old colon-style switch statement (which had a latent bug where a missing break caused unintended fall-through between two size cases) to the modern arrow-style switch expression both fixes the fall-through bug structurally (impossible in the new syntax) and gains compile-time exhaustiveness checking as a bonus safety improvement.

Common follow-ups: What happens if you DO include a default case in an arrow-style switch over an enum -- does the compiler still warn about missing constants?;Why was colon-style switch's fall-through behavior originally designed that way, and is it ever still useful?