The switch Statement in Java
A switch statement compares one value against several possible cases, running the code for whichever case matches — a more readable alternative to a long else-if chain when every branch compares the exact same variable. Traditional switch statements need an explicit break at the end of each case, or execution "falls through" into the next case's code even if its own condition doesn't match, which is a famous, easy-to-forget gotcha.
Modern Java (14+) added switch expressions using arrow syntax, case X -> ..., which don't fall through at all, can directly evaluate to a value the switch itself returns, and let the compiler confirm every possible case is handled — removing the fall-through gotcha entirely for anyone using the new form.
The basic structure
switch (value) { case A: ...; case B: ...; default: ...; } compares value against each case in order.
Fall-through without break
A traditional case without a break at its end keeps executing into the next case's code, whether or not that next case's own value actually matches.
default
Runs when none of the listed cases match, similar to a final else in an if/else if chain.
Arrow-form switch expressions (Java 14+)
case X -> ... never falls through, and the whole switch can evaluate directly to a value.
Exhaustiveness checking
A switch expression over an enum or sealed type can be checked by the compiler to confirm every possible case is actually handled.
public class SwitchDemo { public static void main(String[] args) { int day = 3; String name = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; default -> "Unknown"; }; System.out.println(name); }}Traditional switch with break
Falls through into the next case unless each one ends with an explicit break.
switch (2) { case 1: System.out.println("one"); break; case 2: System.out.println("two"); break;}Arrow-form switch expression
Never falls through, and can evaluate directly to a value instead of just running statements.
int result = switch (2) { case 1 -> 10; case 2 -> 20; default -> 0;};System.out.println(result);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.