Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 201 ยท Control Flow

for Loops

Learn Java for loops - the classic counting loop, for-each over arrays and lists, nested loops, multiple loop variables, loop variable scope and off-by-one bugs.

Many loops follow the same pattern: set up a counter, check it, run the body, update the counter. In a while loop those three parts are scattered over several lines, and forgetting the update gives you an infinite loop. The for loop puts all three in one line at the top, where you can see them at a glance.

Java also has a second kind of for: the for-each loop (officially the enhanced for statement), which walks through every element of an array or collection without any counter at all. Between them, these two loops are the ones you'll write most often. This lesson covers both, plus nested loops, several loop variables, scope rules and the classic off-by-one mistakes.

The classic for loop

Java
for (initialization; condition; update) {
    // body
}

The three parts in the header run in a fixed order:

  1. initialization runs once, before anything else. It usually declares the counter: int i = 0.
  2. condition is checked before every iteration. If it's false, the loop ends.
  3. The body runs.
  4. update runs after each iteration, usually i++. Then back to step 2.
Java Counting up, down and in steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This for loop is exactly equivalent to a while loop, just tidier:

Java
// for version
for (int i = 0; i < 3; i++) {
    IO.println(i);
}

// while version
int i = 0;
while (i < 3) {
    IO.println(i);
    i++;
}

There is one difference: in the for version, i exists only inside the loop. More on that under scope.

Choosing the bounds: off-by-one errors

Programmers count from 0, because Java indexes strings, arrays and lists from 0. The standard loop over something of length n is:

Java
for (int i = 0; i < n; i++)   // i = 0, 1, ..., n - 1  ->  n iterations

Write < with a 0 start and the iteration count equals n. Mixing the styles is the most common loop bug in every language. i <= n with a 0 start runs n + 1 times, and on an array or string it crashes on the last iteration:

Java An off-by-one crash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This example fails on purpose: it prints the four valid characters again and then throws StringIndexOutOfBoundsException for index 4. When you read a loop, check the first and last values of the counter; that's where the bugs live.

Optional parts

All three parts of the header are optional. for (;;) with nothing in it is an infinite loop, the same as while (true). You can also leave out the initialization when the counter already exists, or the update when the body changes the counter itself. These forms are legal but unusual; if you need them, a while loop often reads better.

Multiple loop variables

The initialization can declare several variables of the same type, and the update can contain several expressions separated by commas. A classic use is walking inward from both ends at once:

Java Two indexes moving toward each other

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You can't declare variables of two different types in one header (for (int i = 0, long j = 0; ...) is a compile error). If you need that, declare one of them before the loop.

The for-each loop

When you want every element of an array or collection, in order, and don't need its position, the for-each loop is shorter and impossible to get off by one:

Java
for (Type element : arrayOrCollection) {
    // use element
}

Read the colon as "in": "for each score in scores".

Java for-each over an array and a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

int[] scores = { ... } creates an array, a fixed-size list of values; scores.length is its size. Arrays get their own chapter starting with Arrays. For-each works with arrays and with anything that implements Iterable, which includes every List, Set and Queue, plus a map's entrySet(), keySet() and values() (see The Collections Framework). var works for the loop variable, too.

What for-each can't do

For-each hides the index, and that has consequences:

Java Assigning to the loop variable changes nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • No writing back. The loop variable is a copy of each element. Assigning to it doesn't change the array or list. (If the elements are objects, you can call methods that change those objects, because the copy is a reference to the same object.)
  • No index. If you need the position (to print "item 3 of 5" or compare neighbors), use a classic for.
  • No removing. Removing elements from a collection while a for-each walks through it throws ConcurrentModificationException. Use list.removeIf(...) or an Iterator instead (Iterators and ListIterator).
  • Forward only, one collection at a time. To go backward or walk two arrays in parallel, use a classic for.

A rule of thumb: use for-each by default, and switch to the classic form only when you need one of these things.

Nested loops

A loop inside a loop runs the inner loop completely for each iteration of the outer loop. With an outer loop of 4 and an inner loop of 5, the inner body runs 20 times. That's how you process grids, tables and every pair of items:

Java A multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The inner loop's bounds can depend on the outer variable. Here each row prints as many stars as its number, producing a triangle:

Java Patterns where the inner loop depends on the outer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Starting the inner loop at a + 1 visits each unordered pair exactly once, which is the standard trick for comparing every item with every other item.

Keep an eye on the cost of nesting: two nested loops over n items do about n * n steps. For 1,000 items that's a million, which is fast; for a million items it's a trillion, which is not. Choosing the Right Collection shows how a HashSet or HashMap often removes the inner loop entirely. To leave several nested loops at once, see labeled break in the next lesson.

Loop variable scope

A variable declared in a for header belongs to the loop: it exists during the loop and disappears afterward. That keeps counters from leaking into the rest of the method, and lets you reuse the name i in the next loop.

Java
for (int i = 0; i < 3; i++) {
    // i is visible here
}
IO.println(i);            // error: cannot find symbol: i

int count = 0;
for (int count = 0; count < 3; count++) { }   // error: variable count is already defined

If you need the counter's final value after the loop (for example, the index where a search stopped), declare it before the loop. And unlike some languages, Java doesn't let a loop variable shadow a local variable that is already in scope.

Loop variables and lambdas

Lambdas can only capture variables that are effectively final (never reassigned). A classic for counter changes on every iteration, so it can't be captured; a for-each variable is a fresh variable in each iteration, so it can:

Java
List<Runnable> tasks = new ArrayList<>();

for (int i = 0; i < 3; i++) {
    tasks.add(() -> IO.println(i));         // error: i must be effectively final
}

for (String name : List.of("a", "b")) {
    tasks.add(() -> IO.println(name));      // fine
}

for (int i = 0; i < 3; i++) {
    int copy = i;                           // a new variable per iteration
    tasks.add(() -> IO.println(copy));      // fine
}

You'll use this when you meet Lambda Expressions.

Good habits

  • Don't change the counter inside the body. The header should tell the whole story of how the loop advances.
  • Name counters meaningfully in nested loops. row and col are much easier to follow than i and j.
  • Hoist expensive work out of the condition. The condition runs every iteration. i < list.size() is cheap, but a condition that calls a slow method should store the result in a variable first.
  • Consider streams for transformations. For "filter these, transform those, sum the rest", IntStream.range(0, n) and the Streams API can be clearer. For step-by-step logic with early exits, a loop is usually best.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? for (int i = 0; i < 10; i += 4) { IO.print(i + " "); }

    i takes the values 0, 4 and 8. The next value, 12, fails the condition 12 < 10, so the loop ends.
  2. 2. How many times does the inner body run? for (int r = 0; r < 3; r++) { for (int c = 0; c < 4; c++) { ... } }

    The inner loop runs 4 times for each of the 3 outer iterations, so 3 x 4 = 12.
  3. 3. After int[] a = {1, 2, 3}; for (int x : a) { x = 0; }, what does Arrays.toString(a) return?

    The for-each variable is a copy of each element, so assigning to it changes nothing in the array. Use a classic for with a[i] = 0 to modify elements.
  4. 4. Which loop prints every character of s without crashing?

    Valid indexes run from 0 to length() - 1, so start at 0 and use <. The other loops skip the first character or go one past the end.
  5. 5. What happens with for (int i = 0; i < 3; i++) { } IO.println(i); in a method where no other i exists?

    A variable declared in the for header is scoped to the loop. Declare it before the loop if you need its value afterward.

Summary

  • for (init; condition; update) runs init once, checks condition before each iteration and runs update after each one.
  • Count from 0 with < for n iterations; check the first and last counter values to catch off-by-one errors.
  • The header can declare several variables of one type and update them with commas.
  • for-each (for (Type x : items)) visits every element of an array or Iterable; it can't write back, give the index or safely remove elements.
  • Nested loops run the inner loop fully for each outer iteration, so their cost multiplies.
  • Variables declared in the header exist only inside the loop and can't shadow other locals; for-each variables can be captured by lambdas, classic counters can't.

Next: break, continue and Labels, where you'll exit loops early, skip iterations and escape nested loops in one step.