Explain it simply
Explain it simply
Think of switch as a drinks vending machine. Press 1 and you get a cola, press 2 and you get water, press a number that does not exist and it shows "not available". The machine does not ask a long list of questions like "is it 1? is it 2?"; it looks at the number and goes straight to the matching slot.
When you check one value against a handful of fixed options, such as a menu choice, a day number, an order status or a user role, switch reads more clearly than a long if / else if chain. In modern Java, a switch can even hand the chosen value straight back to you.
Problem → Why → Solution
The problem: Tuesday prints two days
The code below uses Java's older colon-style switch. Run with day = 2, it should print only Tuesday, but it prints Tuesday and Wednesday. The only difference is a missing break; in case 2, and the compiler gives no warning. Bugs like this slip past code review easily, and in important logic such as order status handling they can trigger two actions in a row.
public class Main {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday"); // no break: falls through!
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Unknown day");
}
}
}Why does this happen?
In the colon form, case labels are only entry points into one block of code. Once execution enters at the matching label, it keeps running the statements below until it reaches a break or the end of the switch; this is called fall-through. Arrow labels (case 2 ->), standard since Java 14, never fall through, so this whole class of bug disappears.
Core concept: switch statements and switch expressions
A switch compares one selector value with its case labels. The selector can be an int, char, byte, short (or their wrappers), a String or an enum, and since Java 21 pattern matching allows any reference type. long, double and boolean cannot be selectors. Case labels must be constants and cannot repeat. String cases are compared with equals(), so there is no == problem, but they are case-sensitive.
There are two label styles. The old case 1: falls through, so it needs break. The modern case 1 -> runs exactly one expression, block or throw on its right and never falls through. Several labels can share a case, separated by commas: case 6, 7 ->. One switch cannot mix : and ->.
A switch can also be an expression: String name = switch (day) { ... };. Every case must produce a value, and the whole thing ends with a semicolon. When an arrow needs several statements, write a { } block and hand back the value with yield. You cannot use return there, because return would leave the whole method.
A switch expression must be exhaustive: there must be an answer for every possible value. For int and String that means a default. For an enum, covering every constant is enough and no default is needed; leaving default out is actually better, because adding a constant later makes the compiler report "the switch expression does not cover all possible input values" right away. If the selector is null, any switch without a case null throws a NullPointerException.
| case X: (classic) | case X -> (modern) | |
|---|---|---|
| Fall-through | yes, needs break | never |
| As an expression | possible with yield | yes, value directly |
| Several labels | case 6, 7: | case 6, 7 -> |
- Evaluate the selector once
- Find the matching case or default
- Run the right side of -> (or yield)
- Leave the switch; no fall-through
In a switch expression, the produced value lands in the variable on the left of =.
General pattern
Result result = switch (selector) {
case CONSTANT_A -> valueA;
case CONSTANT_B, CONSTANT_C -> valueBC;
default -> {
yield fallbackValue; // a block can run several statements first
}
};
switch (selector) {
case CONSTANT_A -> doSomething();
default -> doSomethingElse();
}The top half is a switch expression that produces a value and ends with ;. The bottom half is a switch statement that just performs an action. Arrow labels never fall through in either form.
Example: day names, order status and work hours
This example uses three modern forms: a switch expression that produces a value, a switch statement that acts on a String status, and an expression that yields a value from a block. Predict the output for day = 4 and status = "SHIPPED" before checking it.
public class Main {
public static void main(String[] args) {
int day = 4;
String name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6, 7 -> "Weekend";
default -> "Unknown day";
};
System.out.println(name);
String status = "SHIPPED";
switch (status) {
case "PENDING" -> System.out.println("Waiting for payment");
case "SHIPPED", "IN_TRANSIT" -> System.out.println("On the way");
case "DELIVERED" -> System.out.println("Done");
default -> System.out.println("Unknown status: " + status);
}
int hours = switch (day) {
case 6, 7 -> 0;
default -> {
int base = 8;
yield day == 5 ? base - 2 : base;
}
};
System.out.println("Work hours: " + hours);
}
}Code breakdown
- Line 5
String name = switch (day) {Placing the switch on the right of = makes it an expression. The matching case's value lands in name, and the closing }; needs its semicolon.
- Line 11
case 6, 7 -> "Weekend";Two labels share one result. This single line replaces the old trick of stacking case 6: case 7: and relying on fall-through on purpose.
- Line 12
default -> "Unknown day";Cases cannot cover every possible int, so the expression needs default to be exhaustive. Remove it and the code no longer compiles.
- Line 19
case "SHIPPED", "IN_TRANSIT" -> System.out.println("On the way");String cases are matched with equals(), so "SHIPPED" matches and "On the way" is printed. Because it is an arrow, the "Done" line does not run next, and no break is needed.
- Lines 26-29
yield day == 5 ? base - 2 : base;default needs two statements, so it uses a block. yield hands the block's value back to the switch. day is 4, so the result is 8 and "Work hours: 8" is printed.
Thursday
On the way
Work hours: 8Enums and pattern matching switch (Java 21)
A switch expression over an enum needs no default when it covers every constant. Pattern matching for switch, standard in Java 21, lets a type act as a case label: case Integer i -> ... matches when the value is an Integer and creates the variable i. A when guard selects the case only if the pattern matches and the condition is also true. Cases are checked from the top, so the specific case with when must sit above the general case Integer i; the other way round, the compiler reports that the label is dominated. case null handles a null selector instead of throwing a NullPointerException.
public class Main {
enum Size { SMALL, MEDIUM, LARGE }
static int priceOf(Size size) {
return switch (size) { // all constants covered: no default needed
case SMALL -> 1500;
case MEDIUM -> 2000;
case LARGE -> 2500;
};
}
static String describe(Object value) {
return switch (value) {
case null -> "nothing";
case Integer i when i > 100 -> "big number " + i;
case Integer i -> "number " + i;
case String s -> "text of length " + s.length();
default -> "something else";
};
}
public static void main(String[] args) {
System.out.println(priceOf(Size.MEDIUM));
System.out.println(describe(7));
System.out.println(describe(250));
System.out.println(describe("hello"));
System.out.println(describe(null));
System.out.println(describe(3.5));
}
}The output is 2000, number 7, big number 250, text of length 5, nothing and something else. 3.5 is a Double, so it reaches default.
In real projects
Where this shows up in real projects
Workflows such as orders, payments and tickets switch over a status enum (PENDING, PAID, SHIPPED, CANCELLED) to choose a UI label, an email template or the next action. When the switch covers every constant without a default, a teammate who adds a new REFUNDED status immediately gets a compiler error at every switch that must handle it, which beats discovering "Unknown status" in production.
Command-line tools route the command a user types ("add", "list", "quit") through a String switch, and HTTP clients switch on status code / 100 to treat success, redirects, client errors and server errors differently. Pattern switches replace long instanceof chains in code that handles events, message types or the implementations of a sealed interface by type.
Common mistakes
Common mistakes
1. Forgetting break in the colon form
Without break in case 2:, the code of case 3 runs as well. In new code the best fix is to use arrow labels, which simply cannot fall through. In older code that keeps the colon form, check that every case ends with a break.
2. Adding default to an enum switch out of habit
With default -> "Unknown" in place, adding a new enum constant produces no compiler error, and the new constant silently falls into "Unknown". In a switch expression, cover every constant and leave default out, so the compiler's exhaustiveness check keeps working for you.
3. Forgetting about a null selector
If a String status can arrive as null from a request, switch (status) throws a NullPointerException instead of reaching default. Check for null before the switch, or add a Java 21 case null -> label.
Mini challenge
Mini challenge: HTTP status and delivery days
Write two switch expressions: one method that classifies an HTTP status code and one that returns delivery days for a city.
- category(code): switch on code / 100; 2 is Success, 3 Redirect, 4 Client error, 5 Server error, anything else Unknown
- deliveryDays(region): strip and lowercase it; yangon and mandalay take 1 day, bago, mawlamyine and taunggyi 3, anything else 7
- Group labels with commas and use only arrow labels (no break)
- Print exactly the expected output
public class Main {
static String category(int code) {
// TODO: return switch (code / 100) { ... };
return "";
}
static int deliveryDays(String region) {
// TODO: clean the region, then switch with grouped labels
return 0;
}
public static void main(String[] args) {
// TODO: print category for 200, 301, 404, 503 and 99
// TODO: print delivery days for "Mandalay" and "Myitkyina"
}
}Expected: The program prints these seven lines: 200 -> Success 301 -> Redirect 404 -> Client error 503 -> Server error 99 -> Unknown Mandalay: 1 day(s) Myitkyina: 7 day(s)
Show hint
404 / 100 is integer division, so it gives 4. You can write return switch (...) { ... }; directly in the method. String cases are case-sensitive, so lowercase the selector first.
Show solution
public class Main {
static String category(int code) {
return switch (code / 100) {
case 2 -> "Success";
case 3 -> "Redirect";
case 4 -> "Client error";
case 5 -> "Server error";
default -> "Unknown";
};
}
static int deliveryDays(String region) {
return switch (region.strip().toLowerCase()) {
case "yangon", "mandalay" -> 1;
case "bago", "mawlamyine", "taunggyi" -> 3;
default -> 7;
};
}
public static void main(String[] args) {
System.out.println("200 -> " + category(200));
System.out.println("301 -> " + category(301));
System.out.println("404 -> " + category(404));
System.out.println("503 -> " + category(503));
System.out.println("99 -> " + category(99));
System.out.println("Mandalay: " + deliveryDays("Mandalay") + " day(s)");
System.out.println("Myitkyina: " + deliveryDays("Myitkyina") + " day(s)");
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Colon-style case X: falls through without break; use arrow labels case X -> in new code.
- Group labels with commas (case 6, 7 ->), get values straight from a switch expression, and use yield inside blocks.
- Switch expressions must be exhaustive; covering every enum constant without default lets the compiler check you.
- A null selector throws a NullPointerException unless there is a case null, and Java 21 adds type patterns with when guards.