Loops are how you process every item, retry operations and walk through data structures.
Java has four loop forms:
- for — when you count:
for (int i = 0; i < n; i++) { ... }. The three parts are initialization, condition (checked before each iteration) and update. - enhanced for (for-each) — when you visit every element of an array or collection:
for (String name : names) { ... }. No index, no off-by-one errors. Prefer it whenever you don't need the index. - while — when you don't know in advance how many iterations:
while (!queue.isEmpty()) { ... }. - do-while — like while, but the body runs at least once because the condition is checked at the end.
Inside any loop, break exits the loop immediately and continue skips to the next iteration. For nested loops, a label lets you break out of the outer one: outer: for (...) { for (...) { break outer; } }. Use labels sparingly; often extracting a method and returning is clearer.
A variable declared in the for header (int i) exists only inside the loop. If you need the final value afterwards, declare it before the loop.
Common mistakes: using <= instead of < with zero-based indexes (one step too far), and modifying a collection while iterating it with for-each, which throws ConcurrentModificationException. To remove elements while iterating, use list.removeIf(...) instead.
Later you'll see streams, which express many loops (filter, transform, sum) declaratively. Plain loops remain perfectly idiomatic, especially when you need early exit or complex state.
Example
public class Loops {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
sum += i;
}
System.out.println(sum); // 25
String[] words = {"alpha", "beta", "stop", "gamma"};
for (String w : words) {
if (w.equals("stop")) break;
System.out.print(w + " "); // alpha beta
}
System.out.println();
int n = 1;
while (n < 100) n *= 3;
System.out.println(n); // 243
}
}Remember
- Use for-each when you don't need the index
breakleaves the loop,continueskips to the next iteration- Don't add or remove collection elements inside a for-each over it
Watch out for
- Off-by-one:
for (int i = 0; i <= arr.length; i++)reads past the end and throws.