Sub topic 7
Loops: Repeating Work
This chapter assumes you have completed the earlier chapters of this tutorial. In particular, you should be comfortable with:
- Declaring variables with types (Chapter 4)
- Using operators like
+,<, and<=to build expressions (Chapter 5) - Writing
ifandelsestatements to make decisions (Chapter 6)
If those feel shaky, revisit them first. Loops combine all three: you declare a counter variable, compare it with an operator, and change program flow based on the result.
A loop is a statement that repeats a block of code multiple times. Instead of writing the same line five times, you write it once inside a loop and tell Java how many times to run it. Loops matter because repetition is everywhere in software: printing every item in a shopping cart, processing every pixel in an image, or reading every line in a file. Without loops, you would have to copy and paste code, which is slow to write and painful to update.
Java has three loop statements: for, while, and do-while. They can all express the same repetition, but each has a shape that fits certain problems better. This chapter covers all three, plus break and continue for fine-tuning loop behavior, and the mistakes beginners most often make.
The Three Parts of Every Loop
Before looking at syntax, notice that every useful loop needs three pieces of information:
- Initialization — where the loop starts. Example: set a counter to 1.
- Condition — when to keep going. Example: keep going while the counter is 5 or less.
- Update — how the loop moves forward. Example: add 1 to the counter each time.
If you forget any of these, the loop misbehaves. Forget the update, and the loop runs forever. Forget the condition, and Java will not compile the loop. Keep these three parts in mind; each loop syntax simply arranges them differently.
The for Loop
The for loop packs all three parts into one line, which makes it the best choice when you know in advance how many repetitions you want.
public class CountUp {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count is " + i);
}
}
}Output:
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5The line for (int i = 1; i <= 5; i++) has three parts separated by semicolons:
int i = 1— initialization: create a variablei(a common name for "index") starting at 1.i <= 5— condition: checked before every pass. If true, run the body; if false, stop.i++— update: add 1 toiafter each pass.i++is shorthand fori = i + 1.
Here is the order of events, which surprises many beginners: initialization happens once, then the condition is checked, then the body runs, then the update happens, then the condition is checked again.
Note that if the condition is false on the very first check, the body never runs at all. for (int i = 5; i < 5; i++) does nothing.
Counting Down and Stepping
The update does not have to add 1. You can count down, or step by larger amounts:
for (int i = 10; i > 0; i--) {
System.out.println(i);
}
for (int i = 0; i <= 100; i += 10) {
System.out.println(i);
}The first loop counts from 10 down to 1 (i-- subtracts 1). The second loop steps by 10 using i += 10, which is shorthand for i = i + 10.
The while Loop
A while loop states only the condition. The initialization goes before the loop, and the update goes inside the body. This shape fits when you do not know in advance how many repetitions you need — for example, "keep asking the user until they type a valid answer."
public class WhileDemo {
public static void main(String[] args) {
int count = 1; // initialization
while (count <= 5) { // condition
System.out.println("Count is " + count);
count++; // update
}
}
}This prints the same five lines as the for example. The condition is checked before each pass, so like the for loop, a while loop may run zero times if the condition starts out false.
Because the update lives inside the body, forgetting it is a common and serious mistake:
int count = 1;
while (count <= 5) {
System.out.println("Count is " + count);
// count++ is missing!
}This compiles and runs, then prints "Count is 1" forever. The condition count <= 5 never becomes false because count never changes. A program stuck in an endless loop is said to be infinite looping. If this happens while running a program in your terminal, press Ctrl+C to stop it.
The do-while Loop
A do-while loop checks the condition after running the body. This guarantees the body runs at least once, no matter what the condition says.
public class DoWhileDemo {
public static void main(String[] args) {
int count = 10;
do {
System.out.println("Count is " + count);
count++;
} while (count <= 5);
}
}Here the condition count <= 5 is false from the start, yet the program prints "Count is 10" once. The body ran first; the check happened afterward and stopped the loop.
Use do-when — sorry, use do-while — when the work must happen at least once. A typical case is a menu: show the menu, then ask whether the user wants to exit.
Choosing the Right Loop
All three loops can solve the same problem, but picking the one that matches your intent makes code easier to read.
| Loop | Condition checked | Best for |
|---|---|---|
| `for` | Before each pass | A known number of repetitions |
| `while` | Before each pass | An unknown number of repetitions; may run zero times |
| `do-while` | After each pass | Work that must run at least once |
A practical rule: if you can name the start, end, and step, use for. If you are waiting for something (user input, a value crossing a threshold), use while. If the first pass must always happen, use do-while.
break and continue
Sometimes you want to leave a loop early or skip a single pass. Java provides two keywords for this.
break exits the loop immediately. Execution continues at the first statement after the loop:
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}Output:
1
2
3The loop was set up to run ten times, but break ended it after three.
continue skips the rest of the current pass and jumps straight to the next one:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}Output:
1
2
4
5When i is 3, continue skips the print, the update i++ still runs, and the loop resumes with 4.
Common Loop Errors
Three mistakes account for most beginner loop trouble:
- The infinite loop. The update is missing, or it moves the counter the wrong way (
i++in a loop meant to count down). The condition never becomes false. Fix: verify that something in the loop moves toward the exit condition. - Off-by-one errors. You print 4 items instead of 5, or 6 instead of 5. This usually comes from mixing up
<and<=.i < 5runs for 1, 2, 3, 4 (four passes when starting at 1);i <= 5runs five passes. Decide carefully which you mean. - Re-declaring the loop variable. Writing
for (int i = 1; ...)and then inside the body writingint i = 2;is a compile error, becauseialready exists in that scope. Scope is the region of code where a variable is visible. Aforloop's counter exists only inside the loop; after the loop ends,iis gone.
A useful habit: before running a loop by hand, trace it on paper. Write down the value of i at each pass and predict the output. Then run the program and compare.
Loops Connect Forward
Loops pair naturally with the next chapter's topic, arrays. An array is a container holding many values in order, and a loop is how you visit each one. The pattern below previews Chapter 8:
public class LoopAhead {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}Notice the loop starts at 0 and stops at numbers.length - 1 — the condition is i < numbers.length, not <=. Arrays in Java are zero-indexed: the first element is at position 0. That off-by-one detail is exactly the kind of thing loops and arrays will exercise constantly.
Summary
- A loop repeats a block of code. Every loop needs initialization, a condition, and an update.
forbundles all three parts on one line; use it when you know the repetition count.whilechecks the condition before each pass and may run zero times; use it when the count is unknown.do-whilechecks the condition after the pass, so the body always runs at least once.breakexits a loop early;continueskips to the next pass.- Watch for infinite loops, off-by-one errors, and out-of-scope variables.
Exercise
How many lines does this loop print, and what is the last one? for (int i = 2; i <= 8; i += 2) { System.out.println(i); }
Show answer
Four lines: 2, 4, 6, 8. The counter starts at 2 and increases by 2 each pass; the condition fails when i becomes 10.
Exercise
Rewrite the counting loop from the for example using a while loop, keeping the same output (1 through 5).
Show answer
int i = 1; while (i <= 5) { System.out.println("Count is " + i); i++; } — initialization before the loop, condition in the while, update at the end of the body.
Exercise
What is the difference between break and continue inside a loop?
Show answer
break ends the entire loop immediately and continues with the first statement after it. continue ends only the current pass: the update runs, the condition is rechecked, and the loop resumes with the next value.