loops
Why Use Loops?
Loops let you repeat a block of code multiple times without writing it out manually. Java provides three main loop types: for, while, and do-while.
The for Loop
Best used when you know exactly how many times you want to repeat something.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}The for loop has three parts separated by semicolons:
- Initialization —
int i = 1runs once, before the loop starts - Condition —
i <= 5is checked before every iteration; the loop stops once it's false - Update —
i++runs after every iteration
The while Loop
Best used when you don't know in advance how many times you'll loop — you just keep going until a condition becomes false.
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
Warning: Always make sure something inside the loop eventually makes the condition false. Forgetting to updatecounthere would create an infinite loop that never stops.
The do-while Loop
Similar to while, but it checks the condition after running the loop body — guaranteeing the code runs at least once, even if the condition is false from the start.
int count = 1;
do {
System.out.println("Count: " + count);
count++;
} while (count <= 5);The Enhanced for-each Loop
Used to iterate directly over the elements of an array or collection, without needing an index variable.
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}break and continue
Two keywords give you finer control inside a loop:
break — exits the loop immediately
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // stops the loop entirely once i reaches 5
}
System.out.println(i);
}
// Output: 1 2 3 4continue — skips to the next iteration
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skips printing 3, but the loop keeps going
}
System.out.println(i);
}
// Output: 1 2 4 5Nested Loops
A loop can contain another loop inside it — commonly used for working with grids or tables.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i=" + i + ", j=" + j);
}
}Choosing the Right Loop
| Situation | Best Loop |
|---|---|
| Known number of repetitions | for |
| Unknown repetitions, condition-based | while |
| Must run at least once regardless of condition | do-while |
| Iterating over an array or collection | for-each |
Coming up next: Arrays — how to store and work with collections of values under a single variable name.