Control Flow
Control Flow: Overview
Chapter 2 of the Java book. Six lessons take you from a single boolean decision to your first real programs. You'll learn conditions, the four loop shapes, break and continue, arrays, and methods, including Java's pass-by-value rule. Every example is compiled and run, and the recurring traps appear as real compiler errors and exceptions.
Suggest an editControl Flow: Overview
Welcome to Chapter 2. With First Steps behind you — values, numbers, text, I/O — these six lessons give a program the power to decide and to repeat. That's the point where it stops being a calculator and starts being software. You'll make choices with boolean logic and if/switch, repeat work with loops, steer that repetition with break/continue, store many values in arrays, and package logic into reusable methods.
There are six lessons, in this order:
- Booleans & Logic — the yes/no type with no truthiness, comparisons,
&&/||/!, and short-circuit evaluation as a guard. - Conditionals —
if/else if/else, theswitchstatement and its fall-through trap, exhaustiveswitchexpressions, and the ternary?:. - Loops —
while,do-while, the classicfor, and the enhancedfor, plus the off-by-one and infinite-loop traps. - Loop Control & Patterns —
break,continue, labeledbreak, and the accumulation idioms most loops are built from. - Arrays — a fixed block of indexed slots, bounds checking at run time, iteration, jagged 2D arrays, and why an array isn't a growable list.
- Methods — parameters, return types,
void, overloading, and Java's pass-by-value rule (including how object references are passed by value).
Every code block with a ▶ Run button is live — change it, run it again, and watch what the compiler or the JVM says. The fastest way to learn in this chapter is to perturb working examples: move a break, flip a < to <=, forget a return, and see exactly which kind of error you get, compile-time or run-time.
📘 How to read the Intuition boxes. Each one is built in three moves:
- The mechanism — what the compiler and the JVM are actually doing.
- A concrete bite — a specific, runnable failure (often a real compiler error), shown so the trap is visible.
- The earned rule — the decision heuristic, now justified rather than asserted, plus its cost.