Skip to the workspace
Pebellslearn by building
Control Flow, Arrays and Strings  ›  Lesson

Conditionals: if, else and switch

Conditionals 13 minAn if chain runs only the first branch whose condition is true, and a switch expression picks a value from one input among fixed cases.

java / Conditionals: if, else and switch

Explore each scene at your own pace.

01 · The rule

The rule

Conditionals: if, else and switch

An if chain runs only the first branch whose condition is true, and a switch expression picks a value from one input among fixed cases.

Trace the selected branch and the effect of switch fall-through.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.