AP® Computer Science A · Unit 2 · Topic 2.8

The for Loop: Initialize, Test, Update

A for loop packs three jobs into one line: set a starting value, test a condition before each pass, and update the value after each pass. All three work together to control exactly how many times a loop runs.

A for loop exists because looping almost always needs the same three ingredients: a counter to start, a condition to check, and a step to move the counter along. Cramming them into one line - for (init; test; update) - keeps all the control logic for the loop in one place instead of scattered above and inside the loop body, where it's easy to lose track of.

The order never changes. Java runs init exactly once, before anything else. Then, before every single pass, it checks test - if that's false, the loop ends immediately and the body does not run. If test is true, the body runs, and only after the body finishes does update run. Then test is checked again. So the pattern per pass is: test, body, update, test, body, update, and so on, until test fails.

Every for loop can be rewritten as a while loop with identical behavior: write init on its own line, turn the for's test into the while's condition, and place update as the last line inside the while's body. Seeing this equivalence matters because it shows the for loop is not a separate kind of logic - it's a while loop with its bookkeeping organized up front. This connects directly to counting loop passes and to tracing variables row by row, since each pass of a for loop corresponds to one row where init, test, and update each play a specific, fixed role.

Key terms

Initialize
The part of the for loop that runs exactly once, before any testing or looping begins.
Test
The boolean condition checked before every pass; the loop keeps running only while it is true.
Update
The statement that runs at the end of every pass, after the body, usually changing the loop counter.
Pass (iteration)
One complete execution of the loop body, from the start of the body to the end.

Watch it explained

  1. How it worksHow does a for loop run its three parts in a fixed order on every pass?
  2. Worked exampleTrace for (int i = 0; i < 4; i++) and find the value of i at the start of each pass.
  3. Worked exampleFind what for (int i = 10; i > 0; i -= 3) prints and where it finally stops.
  4. Ties togetherHow does every for loop rewrite as a while loop with exactly the same behavior?

Check yourself

Your turn1 of 2
for (int i = 0; i < 21; i++) { } How many times does this loop's body run?

End of topic.