The <code>for</code> Loop in Java
The classic for loop runs a block a controlled number of times, tracking an index explicitly. Use it when you need the index β for a range (0 to n-1), to iterate an array in parallel with another, or to step by something other than 1.
Syntax
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
Three parts separated by ;:
- Init β runs once before the loop.
- Condition β checked before each iteration; loop ends when
false. - Update β runs after each iteration.
Variations
// Count down
for (int i = 10; i > 0; i--) { ... }
// Step by 2
for (int i = 0; i < 100; i += 2) { ... }
// Two variables
for (int i = 0, j = n - 1; i < j; i++, j--) { swap(a, i, j); }
// Infinite
for (;;) {
if (done) break;
...
}
Prefer for-each when you don't need the index
// Index-based
for (int i = 0; i < list.size(); i++) send(list.get(i));
// Enhanced β cleaner
for (User u : list) send(u);
Streams β often clearer
IntStream.range(0, 10).forEach(i -> ... );
IntStream.rangeClosed(1, 100).sum();
Common mistakes
- Off-by-one β
i <= list.size()overshoots by one. Use<. - Using
.length()on arrays β it's.length(no parens). - Modifying the collection inside β triggers
ConcurrentModificationException. Use anIteratororremoveIf. - Loop variable scoped too widely β declare
iinside thefor, not before it.
Related
Pillar: Java control flow. See also for-each, ArrayIndexOutOfBoundsException.