The for Loop
The for Loop
The for loop is Java's most precise looping tool. When you know — or can calculate — exactly how many times you need to repeat something, for gives you all the control in one compact line: where to start, when to stop, and how to advance.
Anatomy of a for Loop
The syntax packs three distinct parts into the loop header, separated by semicolons:
- Initializer — runs once before the loop starts. Typically declares and sets a counter variable.
- Condition — evaluated before every iteration. If
false, the loop ends immediately. - Update — runs after every iteration of the body. Usually increments or decrements the counter.
Counting Up
The most common pattern counts from some starting value up to (but not including) a limit:
Using < rather than <= is idiomatic when working with zero-based indices (arrays, lists), because the valid indices for an array of length 5 are exactly 0 through 4.
Counting Down
Reversing the direction just means starting high, checking with >, and decrementing:
< (exclusive upper bound), while counting down typically uses >= (inclusive lower bound). Being consistent with this convention prevents off-by-one errors.
Custom Step Sizes
The update expression is not limited to i++ or i--. You can use any valid expression — including adding or subtracting a larger step:
You can also multiply or divide for exponential progressions:
Scope of the Loop Variable
When you declare a variable inside the initializer (e.g. int i = 0), that variable exists only inside the loop. Trying to use it after the closing brace is a compile error:
This is intentional and desirable: keeping the counter scoped tightly to the loop prevents accidental reuse and name clashes. If you genuinely need the final value after the loop, declare the variable before the loop:
false, the loop runs forever. A common mistake is an update expression that moves away from the boundary:
for (int i = 0; i < 5; i--) { ... } — i goes negative and never reaches 5. Always double-check that the update moves the counter toward the exit condition.
Multiple Variables in One Header
Java allows multiple initializations and multiple update expressions, separated by commas. This is occasionally useful when two indices need to move in tandem:
for header quickly becomes hard to follow. If you find yourself needing three or more counters, a while loop with the logic spread across its body is usually clearer.
Summary
The for loop consolidates initialization, condition, and update into one readable header. Use it to count up or down with any step size. Remember that a variable declared in the initializer is scoped to the loop — use it freely inside, but declare it outside if you need the final value after the loop ends. In the next lesson we explore the enhanced for-each loop, which trades this fine-grained control for cleaner syntax when iterating over collections.