Control Flow & Loops

The for Loop

15 min Lesson 6 of 14

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:

for (initializer; condition; update) { // body — runs as long as condition is true }
  • 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.
Execution order: initializer → condition check → body → update → condition check → body → update → … → condition is false → loop exits.

Counting Up

The most common pattern counts from some starting value up to (but not including) a limit:

for (int i = 0; i < 5; i++) { System.out.println("i = " + i); } // Output: // i = 0 // i = 1 // i = 2 // i = 3 // i = 4

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.

int[] scores = {88, 72, 95, 60, 84}; for (int i = 0; i < scores.length; i++) { System.out.println("Score " + i + ": " + scores[i]); }

Counting Down

Reversing the direction just means starting high, checking with >, and decrementing:

for (int i = 5; i >= 1; i--) { System.out.println(i + "..."); } System.out.println("Go!"); // Output: // 5... // 4... // 3... // 2... // 1... // Go!
Inclusive vs exclusive bounds: Counting up typically uses < (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:

// Print every even number from 0 to 10 for (int i = 0; i <= 10; i += 2) { System.out.print(i + " "); } // Output: 0 2 4 6 8 10 System.out.println(); // Count down by 3 for (int i = 15; i >= 0; i -= 3) { System.out.print(i + " "); } // Output: 15 12 9 6 3 0

You can also multiply or divide for exponential progressions:

// Powers of 2 up to 1024 for (int n = 1; n <= 1024; n *= 2) { System.out.print(n + " "); } // Output: 1 2 4 8 16 32 64 128 256 512 1024

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:

for (int i = 0; i < 3; i++) { System.out.println(i); // fine } // System.out.println(i); // COMPILE ERROR — i is out of scope here

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:

int i; for (i = 0; i < 10; i++) { // body } System.out.println("Loop ended with i = " + i); // 10 — accessible here
Infinite loop danger: If the condition never becomes 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 (int lo = 0, hi = 4; lo < hi; lo++, hi--) { System.out.println("lo=" + lo + " hi=" + hi); } // Output: // lo=0 hi=4 // lo=1 hi=3 // lo=2 hi=2 (condition fails here, loop ends)
Keep it readable: Using more than two variables in a single 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.