Script Valley
Java: Complete Language Course
Java FundamentalsLesson 1.5

Java for loop, while loop, and loop control

for loop syntax, while loop, do-while loop, enhanced for-each loop, break, continue, nested loops, infinite loop prevention

Loops and Loop Control

Loops repeat a block of code. Choose the loop type based on whether you know the iteration count upfront and what data you are iterating over.

for Loop — Known Count

for (int i = 0; i < 5; i++) {
    System.out.print(i + " ");
}
// Output: 0 1 2 3 4

The initializer, condition, and update are all in the header — the loop structure is visible at a glance. Use this when the iteration count is determined before the loop starts.

while Loop — Unknown Count

int n = 1;
while (n < 100) {
    n *= 2;
}
System.out.println(n); // 128 — first power of 2 >= 100

Use while when the exit condition depends on something computed inside the loop. A do-while variant guarantees at least one execution before checking the condition — useful for user input validation where you need to prompt before you can check.

for-each Loop — Collections and Arrays

int[] scores = {88, 92, 75, 61};
for (int s : scores) {
    System.out.println(s);
}

for-each is cleaner and less error-prone than an index-based loop when you only need element values, not positions.

Loop Control

for (int i = 0; i < 10; i++) {
    if (i == 3) continue; // skip 3
    if (i == 7) break;    // stop at 7
    System.out.print(i + " ");
}
// Output: 0 1 2 4 5 6

break exits the loop entirely. continue skips the rest of the current iteration. Both work in for, while, and do-while loops.

Avoid infinite loops by ensuring the condition eventually becomes false. The most common cause is forgetting to increment the loop variable or mutate state that the condition depends on. When in doubt, add a safety counter as a fallback exit condition during development.