switch
When one value can match many cases — a day of the week, a menu option, an order status — switch is clearer than a long if…else chain. Modern Java's switch expressions with arrows are concise and safe; you'll also need to recognise the older form with break.
Arrow-form switch
void main() { String status = "shipped"; switch (status) { case "pending" -> System.out.println("Preparing your order"); case "shipped" -> System.out.println("On its way"); case "delivered" -> System.out.println("Enjoy!"); default -> System.out.println("Unknown status"); } }
On its way
Each case lists a value and, after ->, what to do. Only the matching case runs. default handles everything else. Switch works with int, char, String, enums (lesson 33) and — with patterns — any type (lesson 49).
Switch expressions
void main() { int day = 6; String type = switch (day) { case 1, 2, 3, 4, 5 -> "Weekday"; case 6, 7 -> "Weekend"; default -> "Invalid day"; }; System.out.println(type); }
Weekend
A switch can produce a value (Java 14+). Several labels can share a case. For an expression, the cases must cover every possible value — otherwise the compiler insists on a default.
Blocks and yield
void main() { String size = "L"; double price = switch (size) { case "S" -> 2.50; case "M" -> 3.00; case "L" -> { double base = 3.00; double extra = 0.70; yield base + extra; } default -> throw new IllegalArgumentException("Unknown size: " + size); }; System.out.println(price); }
3.7
A case can run a block of statements; yield gives the block's result. A case can also throw an exception for impossible values.
The classic switch with break
void main() { int month = 2; int days; switch (month) { case 4: case 6: case 9: case 11: days = 30; break; case 2: days = 28; break; default: days = 31; } System.out.println(days); }
28
The older colon form is still everywhere in existing code. Execution starts at the matching label and falls through into the following cases until it hits a break.
The fall-through bug
void main() { int level = 1; switch (level) { case 1: System.out.println("Bronze"); case 2: System.out.println("Silver"); case 3: System.out.println("Gold"); } }
Bronze Silver Gold
Forgetting break runs every case below the match. The arrow form never falls through, which is one of the reasons to prefer it in new code.
switch vs if
Use switch when you compare one value against several constants. Use if for ranges (score >= 90) and unrelated conditions — although pattern-matching switches with guards (lesson 49) can handle those too.
Try it yourself
Write a tiny calculator with a switch expression.
12.0 / 4.0 = 3.0