Iteration is a fundamental concept in programming—no matter which language you started with. In Java, loops let us repeat a block of code without resorting to copy-paste. In this section, we’ll begin with the for loop, a “definite loop” that neatly packages initialization, condition, body, and update all in one place. Even if you’ve used loops in other languages, you’ll see that Java’s approach is similar, with just a few syntactic details to remember.
Body: The statements that execute on each iteration. Even if there’s only one statement, it’s a good idea to use curly braces { } so you can easily expand the loop later.
Syntax Mistakes: A for loop’s header requires semicolons to separate the three parts, and braces { } around the body if there’s more than one statement. For example:
While understanding proper loop construction helps avoid most issues, sometimes intentional early termination makes code clearer and more efficient. Sometimes you want to stop a loop before its condition naturally becomes false—perhaps when you’ve already found what you’re looking for or encountered an invalid value. In Java, you can exit a loop immediately with the break statement.
Let’s consider an example where we’re searching an array for a special key value. Once we find it, continuing the loop is unnecessary. Here’s how we might use break to exit early:
// Exiting a Loop with break
public class BreakDemo {
public static void main(String[] args) {
int[] numbers = { 3, 8, 12, 5, 7 };
int key = 12;
boolean foundKey = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == key) {
System.out.println("Key found at index " + i);
foundKey = true;
break; // Exit loop immediately
}
}
if (!foundKey) {
System.out.println("Key not found!");
}
}
}
Note: Although break can simplify certain tasks, overusing it may complicate code flow—especially if multiple break statements appear scattered around. Typically, you want your loop condition to govern when you exit, but break is a handy tool for those exceptions when you must bail out early.
Subsection4.2.5Interactive Exercises: Practice with Loops
Now that you’ve seen standard loop patterns, common pitfalls, and the break statement, try these exercises. You may use break where appropriate, but remember to think about the loop’s overall logic and how break affects it.
Off-by-One Exercise. The code below intends to print exactly the first 10 integers, 0 through 9. However, it actually prints 11 values (0 through 10). Study the loop boundaries, and modify the loop so that it produces 10 lines of output, from 0 to 9 inclusive.
Infinite Loop Exercise. The code below never stops. Currently, the loop condition i < 5 remains true forever, because i is not updated inside the loop. Your goal: Insert an update step that ensures i eventually reaches 5, causing the loop to end.
Hint: Typically, you’d increment i, but you might also consider decrementing or adjusting the condition in a different manner. Use whichever approach you prefer, so long as the loop prints 0,1,2,3,4 and then stops.
Summation Exercise. Write a loop that calculates the sum of integers from 1 up to a certain n. Right now, the code is missing the loop logic. Your tasks:
Example: If n is 5, output should be 15. If n is 10, output should be 55. Hint: Consider int sum = 0; before the loop. Carefully pick your starting and ending conditions to include all needed integers.
Besides the for loop, Java also offers while and do-while. Both use a similar idea: run the body repeatedly while a condition holds true. The do-while loop ensures the body runs at least once before checking the condition. We’ll explore these in more detail next, but the principles are largely the same (watch for updates, watch your condition, and guard against infinite loops).
We covered the for loop in Java, highlighting its four parts: initialization, condition, loop body, and update. You saw a simple example that prints numbers from 0 to 9, then explored common pitfalls—off-by-one errors, infinite loops, and syntax gotchas—and practiced them in code. Next, we’ll look at while and do-while, and eventually move on to arrays (so we can loop over large sets of data) and even a custom “iterable” class.