A loop repeats a block while a condition holds. Professionals pick the loop that makes the termination condition obvious.
| Form | Use when |
|---|---|
while | You may run zero times; the condition is not a simple counter |
do-while | You must run once (read a menu, retry a prompt) |
for | Index + bound + step live together |
enhanced for | You visit each element and do not need the index |
Mental model: write the loop so a reader can answer three questions without simulating: What is the first state? What makes it stop? What changes each time so it can stop?
while (scanner.hasNextInt()) {
sum += scanner.nextInt();
}
int guess;
do {
guess = readGuess();
} while (guess != secret);
while tests first. If the condition is false, the body never runs.do-while tests after. The body always runs once. The trailing semicolon is required.i++, node = node.next) is the usual infinite loop.// Incorrect — i never changes
int i = 0;
while (i < 10) {
System.out.println(i);
}
// Correct
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
for (int i = 0; i < n; i++) {
use(a[i]);
}
Three parts: init (once), condition (before each body), update (after each body). Any part may be empty: for (;;) is an infinite loop.
i <= a.length reads one past the end (ArrayIndexOutOfBoundsException).i < a.length, not a cached magic number, unless you measured a need to cache.for (int i = n - 1; i >= 0; i--). Do not write i > 0 if index 0 must run.// Incorrect
for (int i = 0; i <= a.length; i++) { use(a[i]); }
// Correct
for (int i = 0; i < a.length; i++) { use(a[i]); }
for (String name : names) {
System.out.println(name);
}
Iterable (List, Set, …).name = "x" does not change the array. item.setX(1) mutates the object.Iterator or removeIf.NullPointerException.// Incorrect — does not zero the array
for (int n : a) {
n = 0;
}
// Correct
for (int i = 0; i < a.length; i++) {
a[i] = 0;
}
break leaves the innermost switch or loop.continue skips the rest of this iteration (then runs the for update).break / continue names an outer loop. Use it for nested searches. Prefer extracting a method and return when the nest is hard to read.outer:
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (found(grid[r][c])) {
break outer;
}
}
}
There is no break n “break 2 levels” without a label. There is no goto.
A loop inside a loop is O(n × m) if both bounds grow. That is fine for a small grid. It is not fine for “for each user, for each user.”
row/col or i/j consistently. Do not reuse i in the inner loop.Set or a sort + two pointers removes the nest.float increment that skips the bound; while (true) without a reachable break.double counters (for (double x = 0; x != 1.0; x += 0.1)) may never hit equality. Compare with < and a step count.// Incorrect — x may never equal 1.0
for (double x = 0; x != 1.0; x += 0.1) { }
// Correct
for (int i = 0; i < 10; i++) {
double x = i * 0.1;
}
<= length).ConcurrentModificationException.for (int i = 0; i < n; i--) after a copy-paste of the update.for when the index is the story; enhanced-for when the element is the story; while when the condition is the story.~ Good luck with your revision! ~