Modern Java Features
Switch Expressions
Learn modern Switch Expressions with arrow syntax and exhaustiveness checks.
Interview: Commonly tested on arrow syntax, returning values using yield, and compiler exhaustiveness checks.
Introduced in Java 14, Switch Expressions upgrade the legacy switch statement, introducing expression-based returns, arrow labels, and strict compile-time exhaustiveness checking.
Core Idea
Switch expressions return values directly, eliminating break statements and fall-through bugs.
Why It Matters
Exhaustiveness checks ensure that adding a new enum value immediately flags unhandled branches at compile-time.
Interview Lens
Expect questions on arrow syntax vs. colon syntax and returning values using the yield keyword.
Arrow Labels vs. Yield
- Arrow Syntax (
->): Eliminates fall-through behavior. Only the matching block executes, nobreakrequired. yieldKeyword: Used to return a value from a multi-line block inside a switch expression.- Exhaustiveness: The compiler forces the switch to cover all possible input values. For enums, all constants must be handled. For other types, a
defaultblock is required.
Code Walkthrough
This program demonstrates a switch expression returning values using arrow syntax.
public class SwitchExpressionDemo { enum Day { MON, TUE, WED, SAT, SUN }public static void main(String[] args) { Day day = Day.SAT;
// Expression return assignment String type = switch (day) { case MON, TUE, WED -> "Weekday"; case SAT, SUN -> { System.out.println("Weekend reached!"); yield "Weekend"; // Multi-line return keyword } }; // Semicolon required!
System.out.println("Type: " + type); } }
Interview-Relevant Information
Q: Does a switch statement require a semicolon? What about a switch expression?
Answer: A legacy switch statement does not require a semicolon. A switch expression is a statement block that resolves to a value assignment, meaning it must end with a trailing semicolon (};).
Quick Checklist
Why are break statements unnecessary with arrow syntax? When must you use yield? If yes, you understand switch expressions.
Use Cases
Parsing enum configurations directly to database codes.
Routing state machine transitions cleanly.
Common Mistakes
Forgetting the default branch on non-enum switch expressions, throwing compilation errors.
Mixing arrow syntax (->) and colon syntax (:) in the same switch structure.