← The curriculum
§ 1.03 · Foundations

Control flow: if, switch, and loops

Branching and iteration, including modern switch expressions and the enhanced for loop.

Beginner · 20 minute read
Try it yourself
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 1.03.01

if / else if / else

The workhorse. Braces are optional for single statements but always write them — the Apple goto fail bug is the classic warning. Boolean conditions must be actual boolean values; unlike C, if (n) won't compile when n is an int.

§ 1.03.02

Modern switch expressions

Since Java 14, switch is an expression that returns a value and uses arrow syntax. No fall-through, no break, and the compiler checks exhaustiveness for enums and sealed types. Multiple labels on one arm are separated by commas.

Example
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 1.03.03

Pattern matching in switch

Java 21 finalized pattern matching for switch — you can branch on the runtime type of a variable and bind it in the same clause. Combined with sealed interfaces, this replaces most visitor-pattern boilerplate.

Example
Live Java · editable

Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.

§ 1.03.04

for, while, do-while

The classic for (init; cond; step) is best for indexed iteration. while for open-ended loops. do-while for the rare case when the body must run at least once (menu prompts, retry loops).

§ 1.03.05

Enhanced for (for-each)

for (T item : iterable) works on any array or Iterable. It's the default choice unless you actually need the index. When you do need the index, either fall back to a classic for loop or use IntStream.range(0, list.size()).

§ 1.03.06

break, continue, and labels

break exits the nearest enclosing loop or switch; continue skips to the next iteration. Java supports labeled breaks — outer: for (...) { for (...) if (cond) break outer; } — for the rare case of exiting nested loops. Prefer extracting a method and using return when you can.