Java · Medium · Free
Switch expressions (Java 14+) vs classic switch — yield and exhaustiveness?
JavaJava 17+Fresher
Switch expressions
Switch can be an expression returning a value—use -> arrows without fall-through. yield supplies value in statement blocks; compiler checks exhaustiveness for sealed/enums.
- No accidental fall-through with arrow syntax.
- Exhaustive switch on enum/sealed types catches missing cases at compile time.
case nullallowed in pattern switches (Java 21+).- Classic colon switch still exists for side-effect style.
java
String label = switch (status) {
case NEW -> "pending";
case PAID -> "done";
case CANCELLED -> { log(status); yield "cancelled"; }
};Highlight compile-time exhaustiveness—big win for sealed domain models.