Learn Java
import com.learnjava.controlflow.ForLoop;

for Loop in Java

@Concept

A for loop packs initialization, a continuation condition, and an update step into one line, making it the standard choice whenever the number of iterations is known or countable in advance. for (int i = 0; i < 5; i++) runs the initializer once, checks the condition before every iteration, runs the loop body if it's true, then runs the update step — repeating that check-run-update cycle until the condition becomes false.

Any of the three clauses can be left empty — for (;;) is a valid infinite loop, relying on a break inside the body to ever stop — and the loop variable declared in the initializer only exists inside the loop itself, going out of scope the moment the loop ends.

@HowItWorks
1

Initialization

Runs exactly once, before the loop starts, typically declaring and setting a counter variable.

2

Condition check

Evaluated before every single iteration, including the first; the loop body only runs if this is true.

3

Loop body

The code that actually repeats, running once per iteration as long as the condition holds.

4

Update step

Runs after each iteration's body finishes, typically incrementing or decrementing the counter, right before the condition is checked again.

5

Loop variable scope

A variable declared in the initializer exists only for the duration of the loop, and is gone once it ends.

@Example
public class ForLoopDemo {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Count: " + i);
}
}
}
Output
Count: 1
Count: 2
Count: 3
1i starts at 1, and 1 <= 3 is true, so the body runs, printing "Count: 1", then i becomes 2.
22 <= 3 is still true, so the body runs again, printing "Count: 2", then i becomes 3.
33 <= 3 is still true, so the body runs a third time, printing "Count: 3", then i becomes 4.
44 <= 3 is now false, so the loop stops, having printed exactly three lines total.
@UseCases
Repeating an action a known, fixed number of times
Iterating over an array or list by index when the position itself is also needed
Building a countdown or counting sequence from one bound to another
Writing an intentionally empty for (;;) loop that only exits via a break inside it

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Java yourself — building beats watching.