When one value must be compared with several fixed choices, switch is often clearer than a long if-else if chain. Java evaluates the selector once, then jumps to the matching case.
Basic structure
Each case contains a constant followed by a colon. A match runs that branch, break exits the switch, and default handles every unmatched value.
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
}This example covers all seven days. Cases 6 and 7 are adjacent and intentionally share one body because they produce the same result.
break and fall-through
Without break, execution continues into the following case; this is called fall-through. Unless several labels intentionally share one body, end each independent branch with break.
Case labels must be compile-time constants compatible with the selector. Traditional switch supports byte, short, int, char, String, enums, and related wrapper types, but not double.
Execution order
- Evaluate the switch selector.
- Find an equal case; use default if none matches.
- Execute statements from the matched position.
- Exit at break or at the end of the switch.
switch Step Debugger
Choose a membership tier. Click the highlighted line or Run current line; exactly one statement executes each time.
KNOWLEDGE QUIZ
Build a membership checkout calculator
Read a membership tier and order subtotal, use switch to select a discount, and calculate the amount due.
- Read an integer tier and a floating-point amount.
- Tier 0 receives no discount; tiers 1, 2, and 3 receive 5%, 10%, and 15% discounts.
- Use switch to assign discount; print an error and stop for an invalid tier.
- Calculate amount * (1 - discount) and print the amount due with two decimal places.