Loops
Java gives you three ways to repeat a block of code, and they're not interchangeable in style — each one signals something slightly different about what you're actually counting or waiting for.
for — when you know how many times
Reach for a for loop whenever you know, or can calculate, the number of repetitions ahead of time. Its header packs three pieces into one line: a starting point, a condition checked before every pass, and an update run after every pass.
public class Countdown {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
System.out.println(i + "...");
}
System.out.println("Liftoff!");
}
}
5... 4... 3... 2... 1... Liftoff!
The variable i only exists inside the loop's braces — it's scoped there and disappears once the loop finishes, which keeps it from leaking into the rest of your method and causing confusion later.
while — when you're watching for a condition
A while loop is the right shape when you don't know in advance how many iterations it'll take — you just know what has to stay true for it to keep going. A savings goal is a natural fit: you don't know the exact month you'll hit the target, only the condition that means you haven't yet.
public class SavingsGoal {
public static void main(String[] args) {
double balance = 1200.0;
double monthlyDeposit = 350.0;
int months = 0;
while (balance < 3000.0) {
balance += monthlyDeposit;
months++;
}
System.out.println("Reached goal after " + months + " months.");
System.out.println("Final balance: $" + balance);
}
}
Reached goal after 6 months. Final balance: $3300.0
Every while loop needs something inside its body that eventually makes the condition false — here, balance creeping upward each pass. Forget that update, and the loop runs forever, which in a real program means a frozen or unresponsive application.
do-while — when the body must run at least once
A regular while loop checks its condition before the first pass, so if the condition starts out false, the body never runs at all. do-while flips that order: the body runs first, and the condition is only checked afterward, guaranteeing at least one execution. This maps well onto anything phrased as "ask, then keep asking until the answer is acceptable":
public class RetryDemo {
public static void main(String[] args) {
int attempt = 0;
boolean success = false;
do {
attempt++;
System.out.println("Connection attempt " + attempt);
success = (attempt == 3);
} while (!success && attempt < 5);
System.out.println("Connected: " + success);
}
}
Connection attempt 1 Connection attempt 2 Connection attempt 3 Connected: true
break and continue
Sometimes you need to exit a loop early, or skip just one iteration without stopping the whole thing. break exits the loop immediately; continue jumps straight to the next iteration, skipping whatever code comes after it in the current pass.
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
continue; // skip odd numbers
}
if (i > 6) {
break; // stop once we pass 6
}
System.out.println(i);
}
2 4 6
for loop — for (int n : numbers) — which reads each element in turn without needing an index variable at all. It's covered in the next lesson, once there's actually something to loop over.