Card 07/ 09
Fall-Through in a switch Without break
A small drink is charged as small, medium and large, and nothing warns you.
Fall-through is what the older, colon form of switch does when a case has no break: after running the matching case, it carries on and runs every case below it. The code compiles, runs, and adds up to the wrong answer.
A customer orders a small drink and is charged for a small, a medium and a large. Every branch of the switch that prices it is correct on its own.
switch (size) {
case "small":
total += 2;
case "medium":
total += 3;
case "large":
total += 4;
}With size set to "small", total goes up by 2, then 3, then 4: nine in all. The colon form does not choose a branch to run. It chooses a place to start, then runs every line after it until something stops it. break is the statement that stops it (it jumps to the end of the switch), and there is none here.
There are two fixes. Put break; at the end of every branch, which is the older answer. Or write the arrow form, added in Java 14, which never falls through:
int total = switch (size) {
case "small" -> 2;
case "medium" -> 3;
case "large" -> 4;
default -> 0;
};The arrow form runs exactly one branch and, as here, can produce the value directly. So in new code write the arrow form, and in older code check every colon-form case for its break before trusting it.
← → move through sections and cards