Java / Java 21 Coding Standards Interview Questions
Which is better and why: an enhanced switch or an if-else chain for type checks?
| Enhanced switch | if-else chain |
| Compiler checks exhaustiveness when matching a sealed type. | No compiler check; a missing branch is silent until it runs. |
| Reads as a single expression producing one value. | Reads as a sequence of independent statements. |
| Scales cleanly to many variants. | Becomes harder to scan as branches are added. |
For a closed, known set of types - especially a sealed hierarchy - the enhanced switch is the better choice under coding standards, because the compiler actively verifies every case is handled, converting a class of runtime bugs into compile-time errors.
An if-else chain is still reasonable when the conditions are not really about the object's type at all, but about several independent boolean predicates that do not map cleanly onto a single value being matched - forcing that logic into a switch would be less readable, not more.
More Related questions...