Dove's LibraryDove's Library

2.8 - for Loops

A for loop is another type of iteration statement, and its header has three parts: the initialization, the boolean expression, and the update.
for (int i = 0; i < 5; i++) { System.out.println(i); } // prints 0, 1, 2, 3, 4
Here’s how it actually runs:
  1. The initialization (int i = 0) runs once, before anything else.
  1. The boolean expression (i < 5) gets checked. If true, the loop body runs.
  1. After the loop body finishes, the update (i++) runs.
  1. Back to step 2, and repeat, until the boolean expression is false.
The variable being initialized (i in this case) is called the loop control variable.
The loop control variable doesn’t have to start at 0 or go up by 1. The update can be any change, like counting down or skipping:
// counting down by 3 for (int i = 10; i > 0; i -= 3) { System.out.print(i + " "); } System.out.println(); // prints 10 7 4 1 // counting up by 5, using <= so 20 is included for (int i = 0; i <= 20; i += 5) { System.out.print(i + " "); } // prints 0 5 10 15 20
Any for loop can be rewritten as an equivalent while loop, and vice versa:
// This for loop... for (int i = 0; i < 5; i++) { System.out.println(i); } // ...is equivalent to this while loop int i = 0; while (i < 5) { System.out.println(i); i++; }
One difference: a variable declared in the for loop header only exists inside the loop. In the while version, i was declared before the loop, so it still exists afterward (and equals 5).
for (int i = 0; i < 5; i++) { System.out.println(i); } System.out.println(i); // compile error, i only exists inside the loop

AP® is a registered trademark of the College Board, which is not affiliated with Dove's Library and was not involved in the production of, and does not endorse, this website.

Providing free, high-quality AP notes to help students succeed, earn college credit, and reach their educational goals, ensuring everyone has access to the resources they need.

© 2026 Standard Learning Group, Inc., which operates Dove's Library. All rights reserved.