Beginner
Loops: For, While, and Do-While
📂 Phase 1: Java Foundations (Days 1–5) · JavaLoops let you repeat a block of code multiple times without rewriting it — essential for processing collections of data, counting, and repeated calculations.
The For Loop
Best when you know exactly how many times to repeat.
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// Prints Count: 1 through Count: 5
The three parts: int i = 1 (initialization, runs once), i <= 5 (condition, checked before every iteration), i++ (update, runs after every iteration).
The While Loop
Best when the number of repetitions is not known upfront and depends on a condition.
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
The Do-While Loop
Guarantees the loop body runs at least once, since the condition is checked after the first execution.
int num = 10;
do {
System.out.println("Number: " + num);
num++;
} while (num < 5);
// Prints "Number: 10" once, even though 10 < 5 is false
The For-Each Loop
A simplified way to iterate over arrays and collections without managing an index manually.
int[] scores = {85, 90, 78, 92};
for (int score : scores) {
System.out.println(score);
}
Break and Continue
| Keyword | Effect |
|---|---|
| break | Exits the loop immediately, skipping remaining iterations |
| continue | Skips the current iteration only, moves to the next one |
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // stops entirely at i = 5
if (i % 2 == 0) continue; // skips even numbers
System.out.println(i); // prints 1, 3
}
Interview tip: A do-while loop always executes its body at least once — a classic trick question is asking what a do-while prints when its condition starts out false.