for Loop in Java
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.
Initialization
Runs exactly once, before the loop starts, typically declaring and setting a counter variable.
Condition check
Evaluated before every single iteration, including the first; the loop body only runs if this is true.
Loop body
The code that actually repeats, running once per iteration as long as the condition holds.
Update step
Runs after each iteration's body finishes, typically incrementing or decrementing the counter, right before the condition is checked again.
Loop variable scope
A variable declared in the initializer exists only for the duration of the loop, and is gone once it ends.
public class ForLoopDemo { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { System.out.println("Count: " + i); } }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.