Conditionals: if, else and switch
Brew Bar gives a discount on big orders: 10 or more cups cost 200 cents each, 5 to 9 cost 225, and anything smaller costs the full 250. The till has to pick exactly one of those prices. Conditionals are how a program chooses between paths.
The rule
Conditions are checked top to bottom; the first true one wins.
An if chain tests conditions in order and runs only the first branch whose condition is true:
int cups = 12;
int unitCents;
if (cups >= 10) {
unitCents = 200;
} else if (cups >= 5) {
unitCents = 225;
} else {
unitCents = 250;
}Twelve cups passes the first test, so unitCents is 200 and the remaining tests are never looked at. Conditions are built from comparisons (==, !=, <, <=, >, >=) joined by && (and), || (or) and ! (not).
&& and || short-circuit: they stop as soon as the answer is known. In card != null && card.isActive(), if card is null the right side never runs, which is exactly what stops a crash.
For a tiny either-or, the ternary operator fits on one line:
String label = points >= 100 ? "gold" : "member";When you are choosing by one value among several fixed options, a switch expression (modern Java) is clearer than a long chain. Each case uses an arrow, and the whole switch produces a value:
int sizeCents = switch (size) {
case "S" -> 250;
case "M" -> 300;
case "L" -> 350;
default -> throw new IllegalArgumentException("Unknown size: " + size);
};Arrow cases never "fall through" into the next case, and a switch expression must cover every possible input. For a String, that means a default is required.
The shortcut
With ranges, order the tests from the most demanding to the least. Then each later test can assume the earlier ones failed, and you never need to write an upper limit.
Test the strictest first
Is
7 >= 10? No, move on.
Drills
Answer fast — trust the rule.
With cups = 12, the chain is if (cups >= 5) deal = "bulk"; else if (cups >= 10) deal = "party"; else deal = "none";. What is deal?
With points = 100, what is points >= 100 ? "gold" : "member"?
card is null. What does card != null && card.isActive() do?
A switch expression on a String size has cases for "S", "M" and "L" but no default. What happens?
Remember
- Conditions are checked top to bottom; the first true one wins.
- Order range tests from strictest to loosest.
- Traps: a loose test placed first, and a switch expression with no
default.
