Switch Statement
In short: A control structure that checks a value against several possible cases and runs a different code block depending on the match — a more readable alternative to a long chain of if…else conditions.
In more detail: Every case branch stands for a possible value of the variable being checked; a default branch catches all uncovered cases. In many classic languages, execution “falls through” into the next branch with no explicit break (fallthrough) — a common beginner mistake. More modern language variants (e.g. Java from version 14) now also offer an expression form with no fallthrough risk.
In Depth
The classic fallthrough pitfall:
switch (day) {
case 6:
System.out.println("Saturday");
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Weekday");
}
// for day == 6, this PRINTS: "Saturday" AND "Sunday" - even though only
// case 6 matches! Without break, execution just "falls" through.Without break at the end of every case branch, execution simply continues into the NEXT branch, regardless of whether its condition even matches — a behaviour many other control structures (like if…else) don’t have, which is why it especially surprises beginners. This fallthrough behaviour is sometimes even deliberately intended (several case values should run the same code — then several case lines are deliberately left in a row with no break), but is significantly more often simply a forgotten break.
Modern language variants address this problem structurally: Java’s newer “switch expression” syntax (from version 14) with -> instead of : no longer falls through by default:
String result = switch (day) {
case 6, 7 -> "Weekend"; // several values, ONE branch, no fallthrough
default -> "Weekday";
};A switch statement is worthwhile especially when a SINGLE variable is checked against several fixed, known values — for more complex conditions (several variables, range checks like “between 10 and 20”), an if...else chain is usually still the clearer choice, since switch in most languages only supports exact equality comparisons.
See also: if…else, Break/Continue