Switch Expressions (Java 12+): Arrow Syntax
You'll learn: How modern Java switch expressions use arrow syntax to eliminate fall-through and return values cleanly.
What's Different Now?
Starting with Java 12, you can use switch expressions with a new arrow (->) syntax. Unlike traditional switch statements with their fall-through behavior and break keywords, the arrow syntax treats each case as an independent expression that automatically returns a value—no fall-through, no break needed.
Think of it like a vending machine upgrade: the old version required you to manually stop the dispensing mechanism after each selection (using break), or everything below would also fall out. The new version automatically stops after giving you exactly what you selected.
The Arrow Syntax
Instead of writing:
case value: code; break;
You write:
case value -> expression;
The arrow syntax means "when this case matches, evaluate this expression and we're done." Each case is isolated—no accidental fall-through.
int day = 3;
String dayType = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
// dayType is "Weekday"
Notice how the switch now returns a value that you can assign directly! Each arrow case automatically produces the result on its right side. You can also group multiple values with commas.
For single expressions, it's clean and simple. The compiler ensures you've covered all possible cases (or included default).
Key Takeaway: Arrow syntax in switch expressions eliminates fall-through, removes the need for break statements, and allows switch to return values directly—making your code safer and more concise.