Course contentsShow
← Java
Lesson 612 of 2,87014. EnumerationsFree lesson

Exhaustive Switch Coverage and Compiler Warnings

Understand how the compiler enforces complete coverage of enum constants in switch statements.

Exhaustive Switch Coverage and Compiler Warnings

You'll learn: How the Java compiler helps you ensure every enum constant is handled in a switch statement.

When you use an enum in a switch statement, the compiler has a powerful trick up its sleeve: it knows exactly which constants exist. Unlike switching on an int or String, where the possibilities are endless, an enum has a finite, known set of values. The compiler uses this knowledge to protect you from mistakes.

The Compiler's Safety Net

When you write a switch on an enum without a default case, the compiler checks whether you've covered all possible constants. If you miss even one, it issues a warning (or in modern Java with switch expressions, an error). This is called exhaustive coverage.

Think of it like a checklist at airport security: if your enum has three constants but your switch only handles two, the compiler says, "Wait — what happens with the third one?"

enum Status { PENDING, APPROVED, REJECTED }

public void processStatus(Status status) {
    switch (status) {
        case PENDING:
            System.out.println("Awaiting review");
            break;
        case APPROVED:
            System.out.println("Approved");
            break;
        // Missing REJECTED — compiler warns!
    }
}

Why This Matters

If you later add a new enum constant (like Status.ON_HOLD), every switch without exhaustive coverage will immediately warn you. This catches bugs at compile-time rather than letting them lurk as runtime surprises.

With switch expressions, exhaustiveness is even stricter — the code won't compile at all unless every case is covered or a default is provided.

Key Takeaway:
The compiler enforces exhaustive coverage for enum switches, warning or erroring when constants are unhandled — your safety net against missing cases when enums evolve.