Java Reference ยท Keywords and Statements
The for statement
Reference for the Java for loop: initialization, condition and update, multiple variables, omitted parts, scope, and common off-by-one mistakes.
The basic for statement repeats a body while a condition holds. Its header has three parts separated by semicolons: an initialization that runs once, a condition checked before every iteration, and an update that runs after every iteration. It is the usual choice when you need an index or a fixed number of repetitions.
Every part of the header is optional. for (;;) is an infinite loop that you leave with break, return or an exception.
for (int i = 0; i < 5; i++) { System.out.println(i); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
for (initialization; condition; update) {
body
}
| Part | Description |
|---|---|
initialization |
A local variable declaration (all of the same type, comma separated) or a list of expression statements. Runs once. |
condition |
A boolean expression checked before each iteration. If omitted it is true. |
update |
A comma-separated list of expression statements run after each iteration, before the condition is checked again. |
Usage notes
- Scope: a variable declared in the initialization exists only inside the loop. Declare it before the loop if you need it afterwards.
- Off-by-one errors: for an array of length
n, valid indexes are0ton - 1, so usei < n, noti <= n. - Lambdas and inner classes can only capture variables that are effectively final. The loop variable
iis changed byi++, so copy it into a final local first. - Modifying the counter inside the body is legal but makes loops hard to read.
- Floating-point counters accumulate rounding error (
for (double x = 0; x != 1; x += 0.1)never ends). Count with anintand compute the value. - Overflow:
for (byte b = 0; b < 200; b++)never ends becausebytewraps around at 127. - Collections: when you do not need the index, the for-each loop is shorter and cannot go out of bounds.
- Removing from a list while looping upward skips elements; loop downward or use
removeIf. breakandcontinuework as in other loops;continuejumps to the update part.