Card 07/ 09

GotchaDifficulty: Intermediate1 min

Why a switch Without break Keeps Going

Somebody reports that ordering the small size charges them for small, medium and large. The switch looks right and every branch is correct on its own.

java
switch (size) {
    case "small":
        total += 2;
    case "medium":
        total += 3;
    case "large":
        total += 4;
}

With size set to "small", total goes up by nine. The colon form of switch does not choose a branch — it chooses a place to start, and then runs everything after it until something stops it. break is what stops it, and there is not one here.

Two fixes. Put break; at the end of every branch, which is the old answer. Or write the arrow form, which was added in Java 14 and does not fall through at all.

java
int total = switch (size) {
    case "small" -> 2;
    case "medium" -> 3;
    case "large" -> 4;
    default -> 0;
};

Prefer the arrow form in anything new. It removes a whole class of bug by removing the thing that caused it, and it can produce a value, which the colon form cannot.