Control Flow
Branch with if and switch expressions, and repeat work with for, while, and do-while loops.
Why it matters
Start from the concept, not the syntax
Meet a concrete situation where this idea earns its place, then state the boundary it guards.
A program gets interesting when it makes decisions and repeats work. Java gives you a small set of tools for both—branches and loops—and modern switch expressions remove the classic pitfalls that made branching error-prone.
By the end of this chapter
Missing breaks and off-by-one loop bounds make control flow skip cases or run one time too many or too few.
- if versus switch
- Loop selection
- break and continue
Mechanism
How Java expresses the concept
Walk the actual types, rules, and runtime behavior involved—the same behavior described in the Java Language Specification.
The mental model
`if`/`else if`/`else` runs blocks based on boolean conditions. Conditions must be boolean; you cannot write `if (x)` for a non-boolean `x` as you can in some languages.
A `switch` statement picks a branch by value. Modern Java adds switch expressions with `->` and exhaustive checking: `int days = switch (month) { case 1,3,5 -> 31; ... };`. The new form returns a value and does not fall through, which removes a whole class of missing-break bugs.
`for` runs a known number of times, the enhanced `for` (for-each) iterates over any `Iterable` or array cleanly, `while` repeats while a condition holds, and `do-while` runs at least once. `break` exits the nearest loop or labelled block; `continue` skips to the next iteration.
Prefer the enhanced for loop when you only read elements; it is shorter and cannot go out of bounds. Reach for indexed `for` only when you need the index.
Concept map
Inspect the building blocks as a whole
Use the map as a structural reference; it shows the pieces and their relationships, not an execution sequence.
Core Java
Branches, loops, and switch
Control flow decides which statements run. Java offers if/else, switch (now with expressions), and three loop forms.
- 01Boolean conditions
- 02if / else if / else
- 03Switch expressions
- 04for and enhanced for
- 05while and do-while
- 06break and continue
Implementation
Encode the smallest runnable example
Write and run the code, then observe the behavior you just predicted with a real Java program.
Runnable snippet path
Predict, run, and change each example
Switch expression returns a value
The arrow form yields a result and is exhaustive when the type is sealed or has a default.
public class Season {
static int daysIn(String month) {
return switch (month) {
case "Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec" -> 31;
case "Feb" -> 28;
case "Apr", "Jun", "Sep", "Nov" -> 30;
default -> throw new IllegalArgumentException(month);
};
}
}Remember
Arrow-case switch does not fall through; add a default or the compiler demands exhaustiveness.
Change one input, predict the result, then compile or test it before continuing.
Loop with the enhanced for
Iterate a fixed list without managing an index counter.
import java.util.List;
public class Total {
public static void main(String[] args) {
int sum = 0;
for (int n : List.of(1, 2, 3, 4)) {
sum += n;
}
System.out.println(sum);
}
}Remember
Use the enhanced for when you read values; use indexed for when you need the position.
Expected output
10
Watch out
Break it on purpose, then repair the right layer
Predict the symptom before running the failure case, and close with the completion checklist.
Deliberate failure
Break
Use a classic switch without break on shared cases
Observe
Execution falls through and returns the wrong day count
Repair
Prefer the arrow switch expression so cases cannot fall through and the compiler checks exhaustiveness
Why it matters
Prefer the arrow switch expression so cases cannot fall through and the compiler checks exhaustiveness
Completion checklist
- Choose if versus switch deliberately
- Pick the loop shape that fits the task
- Exit or skip iterations with break and continue
Go deeper
Official references
The primary sources behind this chapter. Every claim above stays consistent with them.