Java switch
›Short versionOpen if you only have a minute.
- switch matches one value against case labels, then starts running at the label that matches.
- In the classic colon form, a case does not end at the next case. Execution falls through until a break.
- A missing break runs the later cases as well. The program still compiles.
- case 6: case 7: shares one body on purpose. That is fall-through you meant. A forgotten break is fall-through you did not.
- The arrow form, case 2 ->, does not fall through. default handles the value no case claimed.
A is for several exact values of one expression: a day number, a command name, an enum. Ranges and overlapping tests stay with if...else. The failure that belongs to switch is .
int day = 2;
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");
break;
}day matches 2, the method prints Tuesday, and leaves the switch. Wednesday is not printed. Take the breaks out and the same input prints Tuesday and then Wednesday, because matching case 2 starts a run that keeps going.
The next label is not a wall
This is the same day, with the stops removed between Tuesday and Wednesday. The compiler accepts it. The console is the only place the extra line shows up.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other");
}What the console shows
Tuesday Wednesday
runs when nothing matched. Here, day 9 would print Other. A switch that has no default does nothing for an unmatched value, which looks like success if you only tested the cases you listed. Put default last, and break out of it too if any case sits below it.
The arrow form does not use this rule. case 2 -> System.out.println("Tuesday"); runs that one path and leaves. There is no break to forget. Choose the arrow form when each value should do one thing. Keep the colon form when you are deliberately sharing a body across labels.
In the switch above, day is 2, and case 2 has no break before case 3. What prints? What prints if day is 3?
Day 2 prints Tuesday and then Wednesday. Matching case 2 starts execution there, and case 3 is only a label, so the Wednesday line runs until the break under it. Day 3 prints Wednesday alone. Execution started at case 3, and the Tuesday line is above the start, so it is not visited.