
🧠 Lesson: Exhaustiveness of switch Statements in Java
(with French Poet Examples)
When using Java’s enhanced switch statement (with pattern matching or null labels), the compiler requires that the switch be exhaustive. This means that all possible input values must be accounted for.
❗ When Is Exhaustiveness Required?
A switch statement must be exhaustive when:
🟣 It uses pattern matching (like case String s: or case Integer i:),
🟣 It uses null as a case label,
🟣 Or the selector expression is not one of the legacy types:
char, byte, short, int, their wrapper types, String, or an enum.❌ Example: Incomplete switch — Does Not Compile
In the following code, we’re trying to classify French poets using pattern matching. But we forgot to handle all possible input types, so the code doesn’t compile:
⚠️ The compiler complains because it’s possible to pass in other object types, like a Double, null, or a custom class — and those aren’t handled here.
✅ Solution: Add a default Case to Make It Exhaustive
To fix this, we can add a default clause to cover all remaining possibilities:
Now the switch is exhaustive — it handles any Object type.
✅ Takeaway
When using pattern matching in switch, always ensure exhaustiveness by either:
🟣 Covering all logical patterns, or
🟣 Adding a default clause.
Otherwise, Java will refuse to compile your code.