Card 04/ 09

ComparisonDifficulty: Intermediate2 min

if vs switch: Choosing by What the Branches Test

Ranges and mixed tests suit an if ladder; one value against fixed constants suits a switch.

if and switch can both choose between paths, and each can be forced to do the other's job. This card compares them on what they test and what the compiler checks for you, and ends with a rule for choosing.

Forced into the wrong job, each one gets awkward. A switch asked to express a range needs a case for every value in it. An if ladder asked to look up a code becomes twenty rungs that all compare the same variable, one after another.

The two branching statements on what they test, what they accept and what the compiler checks
Compared onif / else ifswitch
TestsA condition per rungOne value against constants
AcceptsAnything that produces true or falseint, char, String, an enum, and in Java 21 any object through type patterns
RangesNaturalNot on an int: every value has to be listed
Many values, one outcomeA long chain of || (or)Comma-separated on one case
Every value handledNothing checks itChecked by the compiler for a switch expression over an enum or sealed type

The decision rule. Ask what the branches are testing. If every rung compares the same variable with a constant, write a switch. If the rungs test different things, or the same thing with > and <, write an if ladder.

The last row matters most in real code. An enum is a type with a fixed list of named values, such as the tiers BRONZE, SILVER and GOLD. A switch expression over it, written without a default, must handle every value, so the day somebody adds PLATINUM the build fails with "the switch expression does not cover all possible input values", instead of giving a wrong answer at run time. A switch statement, and an if ladder, get no such check: they compile, and the new value falls through to whatever the code does by default.

So when an if ladder compares one variable with constants, rewriting it as a switch expression makes it shorter and lets the compiler catch the case you forgot.