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.