Part 03 / Topic 2 of 8
Classic switch: a statement with case and break
A switch checks one value against several case labels. It is a cleaner alternative to a long else-if ladder when every branch compares the same variable to different exact values.
int menuChoice = 2;
switch (menuChoice) {
case 1:
System.out.println("1. Check balance");
break;
case 2:
System.out.println("2. Deposit");
break;
case 3:
System.out.println("3. Withdraw");
break;
default:
System.out.println("Invalid choice");
}
Output:
2. Deposit
break stops the switch right there. Leave it out, and execution falls through into the next case, running it too — rarely what you want:
int menuChoice = 2;
switch (menuChoice) {
case 1:
System.out.println("1. Check balance");
case 2:
System.out.println("2. Deposit");
// no break here on purpose: execution falls into case 3 too
case 3:
System.out.println("3. Withdraw");
break;
default:
System.out.println("Invalid choice");
}
Output:
2. Deposit
3. Withdraw
Fall-through is only useful on purpose, to group cases that share one action — stack the labels with nothing between them:
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
System.out.println("Passed with a good grade");
break;
case 'C':
case 'D':
System.out.println("Passed");
break;
case 'F':
System.out.println("Failed");
break;
default:
System.out.println("Unknown grade");
}
Output:
Passed with a good grade
A switch can check an int, a char, a String, or an enum (Part 8) — not a boolean or a double.
Full program: examples/02_switch_statement_and_expression.java.
Done here? The practice set for Part 3 — including the solutions — is on the part page.