Control flow: if, switch, and loops
Branching and iteration, including modern switch expressions and the enhanced for loop.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
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.
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.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
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.
Runs on a sandboxed JVM via the public Piston API. Edit the code and hit Run.
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).
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()).
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.
Related lessons & next topics
Keep going — these pair well with Control flow: if, switch, and loops.
- § 1.01 · FoundationsHello, World — your first Java program
Set up the JDK, understand the anatomy of a Java class, and run a program from the command line.
Beginner · 12 min - § 1.02 · FoundationsVariables, primitive types, and references
The eight primitive types, the difference between values and references, and how the compiler infers types.
Beginner · 18 min - § 2.01 · Object-Oriented JavaClasses, fields, constructors, methods
Model the world with classes — encapsulation, constructors, the `this` reference, and method overloading.
Beginner · 25 min - § 2.02 · Object-Oriented JavaInterfaces, abstract classes, inheritance
Polymorphism done right — when to extend, when to implement, and why composition usually wins.
Intermediate · 28 min