switch Statements and Expressions
Overview
Java has two forms of switch:
| Form | Introduced | Returns a value? |
|---|---|---|
switch statement |
Java 1.0 | No |
switch expression |
Java 14 (final) | Yes |
Both support the traditional colon (:) syntax and the newer arrow (->) syntax.
switch Statement — Colon Syntax
javaint day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other");
}Fall-through: Without break, execution continues into the next case.
javaswitch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
break;
case 6:
case 7:
System.out.println("Weekend");
}switch Statement — Arrow Syntax
Arrow cases do not fall through:
javaswitch (day) {
case 1 -> System.out.println("Monday");
case 2 -> System.out.println("Tuesday");
case 3 -> System.out.println("Wednesday");
default -> System.out.println("Other");
}Multiple labels per arrow case:
javaswitch (day) {
case 1, 2, 3, 4, 5 -> System.out.println("Weekday");
case 6, 7 -> System.out.println("Weekend");
}switch Expression — Arrow Syntax
A switch expression produces a value and must be exhaustive (all possible values covered):
javaString name = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
case 6 -> "Saturday";
case 7 -> "Sunday";
default -> throw new IllegalArgumentException("Invalid day: " + day);
};switch Expression — Colon Syntax with yield
Use yield to return a value from a colon-style switch expression block:
javaint numLetters = switch (day) {
case 1, 2, 3, 4, 5, 6 -> day + 5; // simple arrow
case 7 -> {
System.out.println("Computing Sunday...");
yield 6; // yield required in a block
}
default -> 0;
};
yieldvsreturn:yieldexits theswitchblock with a value;returnexits the enclosing method.
Allowed Selector Types
| Type | Allowed in switch |
|---|---|
byte, short, int, char |
Yes |
Byte, Short, Integer, Character |
Yes |
String |
Yes (since Java 7) |
enum |
Yes |
long, float, double, boolean |
No |
| Any reference type (patterns) | Yes (since Java 21) |
Exhaustiveness
- A
switchstatement does not need to be exhaustive — missing cases are simply skipped. - A
switchexpression must be exhaustive — the compiler enforces this. Usedefaultor cover all enum constants.
Key Rules Summary
| Concept | Colon syntax | Arrow syntax |
|---|---|---|
| Fall-through | Yes | No |
| Multiple labels | case 1: case 2: |
case 1, 2 -> |
| Value from block | yield |
yield |
| Break needed? | Yes (to stop fall-through) | No |