Lesson 3: Control Flow: if/else, switch, loops

04 Jul 2026 1 min Swarnil Singhai

Control flow decides which code runs — the same three constructs (branch, switch, loop) power everything from form validation to fraud checks.

Real-time example

A ride-hailing app's surge-pricing engine branches on demand ratio, then loops over nearby drivers to notify them.

double demandRatio = requests / (double) availableDrivers;
String tier;
switch ((int) Math.min(demandRatio, 3)) {
    case 0 -> tier = "normal";
    case 1 -> tier = "surge-1.5x";
    default -> tier = "surge-2x";
}
for (Driver d : nearbyDrivers) {
    d.notify(tier);
}

What's happening

Modern switch expressions (Java 14+) return a value directly instead of falling through — fewer bugs than classic switch-case.

Prefer switch expressions over chained if/else once you have more than 3 branches on the same variable.

Advertisement