Loops
Loops let you repeat a block of code without writing it out multiple times. Java provides four looping
constructs: for, while, do-while, and the enhanced for-each
loop, plus break and continue to control their flow.
The for Loop
Best when you know in advance how many times you want to repeat something. It bundles initialization, condition, and update into one line.
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// i = 0, i = 1, i = 2, i = 3, i = 4
The while Loop
Repeats as long as its condition stays true. The condition is checked before each iteration, so the body might not run at all.
int count = 0;
while (count < 3) {
System.out.println("count = " + count);
count++;
}
The do-while Loop
Similar to while, but the condition is checked after each iteration. That means a
do-while loop's body always runs at least once, even if the condition is false from
the start.
int count = 10;
do {
System.out.println("This runs once, count = " + count);
count++;
} while (count < 3);
while loop with the same false-from-the-start condition would never run its body. That's the key difference — do-while guarantees at least one execution.The Enhanced for-each Loop
A cleaner way to iterate over every element of an array or collection when you don't need the index.
int[] numbers = {10, 20, 30};
for (int n : numbers) {
System.out.println(n);
}
// 10, 20, 30
break and continue
break exits a loop immediately. continue skips the rest of the current iteration and
moves on to the next one.
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue; // skip printing 3
}
if (i == 6) {
break; // stop the loop entirely
}
System.out.println(i);
}
// 0, 1, 2, 4, 5
Nested Loops
A loop can contain another loop inside it. This is common when working with grids or 2D data.
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 2; col++) {
System.out.println("row " + row + ", col " + col);
}
}
for when you know the iteration count, while when you don't, and for-each whenever you just need to visit every element. Next up: Arrays, where loops get put to real use.