Exhaustiveness in Switch Expressions
You'll learn why switch expressions must cover every possible value, ensuring your code always produces a result.
Why Exhaustiveness Matters
In traditional switch statements, you could list a few cases and omit the rest—the code would simply skip over unmatched values. But switch expressions are different: they must produce a value to assign to a variable or return from a method. If Java can't guarantee that every possible input will produce a result, your code won't compile.
Think of it like a vending machine that must dispense something for every valid coin combination. If there's a possibility no product comes out, the machine is broken. Similarly, a switch expression must account for all possibilities.
How Java Enforces Exhaustiveness
When you write a switch expression, the compiler checks whether you've covered all possible values of the type you're switching on:
- For enums: You must either list all enum constants or include a
defaultcase. - For primitive types (like
int,char): You must include adefaultcase, since there are too many values to list individually. - For Strings: You must include a
defaultcase.
If you forget a case and don't provide default, the compiler will refuse to build your code. This prevents runtime surprises where a value slips through unhandled.
The Guarantee
This exhaustiveness check is what makes switch expressions safe for assignments. Because every path must yield a value, Java knows your variable will always be initialized, and your logic will always complete.
Key Takeaway:
Switch expressions require complete coverage of all possible cases (or a default) so the compiler can guarantee a value is always produced—no unhandled paths allowed.