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:
- The initialization (
int i = 0) runs once, before anything else.
- The boolean expression (
i < 5) gets checked. If true, the loop body runs.
- After the loop body finishes, the update (
i++) runs.
- 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