Loops: for, while & do-while
Counted and conditional loops, the enhanced for, break, continue, labels and nested loops.
Computers are brilliant at doing the same thing many times without getting bored. A loop repeats a block of code: printing every item in a list, retrying until the user enters a valid password, adding up a million numbers. Java has four kinds of loop, plus break and continue to control them.
while: repeat while a condition is true#
The condition is checked before each pass. If it is false at the start, the body never runs. Something inside the loop must eventually make the condition false (here n--), or you get an infinite loop. Press Ctrl+C in the terminal to stop a runaway program.
while is ideal when you do not know in advance how many repetitions you need:
do-while: run at least once#
A do-while checks the condition after the body, so the body always runs at least once. It is perfect for menus and "ask until valid" input:
Note the semicolon after while (...) at the end.
for: counted loops#
When you know how many times to repeat, the for loop keeps the counter logic in one place:
The header has three parts separated by semicolons:
- Initialisation
int i = 0: runs once before the loop. - Condition
i < 5: checked before every pass; the loop stops when it is false. - Update
i++: runs after every pass.
The counter i exists only inside the loop. Any step works:
Off-by-one errors are the most common loop bug.
i < 5runs 5 times starting from 0;i <= 5runs 6 times. When looping over an array of lengthn, usei < nbecause indexes go from 0 to n - 1.
The enhanced for (for-each)#
To visit every element of an array or collection, the enhanced for is shorter and cannot go out of bounds:
Read for (String lang : languages) as "for each lang in languages". The trade-off is that you do not get the index, and assigning to the loop variable does not change the array. Use a classic for when you need the index or want to modify elements.
break: leave the loop early#
break jumps out of the loop immediately. It is handy for searching:
continue: skip to the next iteration#
continue skips the rest of the current pass and moves on to the next:
Nested loops#
A loop inside another loop runs the inner loop completely for every pass of the outer loop. Classic uses are grids, tables and pattern printing:
%4d prints an integer right-aligned in a field 4 characters wide, which keeps the table neat. If the outer loop runs n times and the inner loop runs n times, the body runs n * n times, so nested loops get slow quickly on big inputs.
Labelled break and continue#
Plain break only exits the innermost loop. To exit an outer loop, put a label before it:
Labels are rarely needed. Often extracting the search into a method and using return is cleaner.
Choosing the right loop#
A worked example: number-guessing game#
new Random().nextInt(1, 101) (Java 17+) returns a random int from 1 up to, but not including, 101. With a good strategy (always guess the middle), you never need more than 7 attempts. That idea is called binary search.
Common mistakes#
- Infinite loops: forgetting to update the counter, or updating the wrong variable.
- Off-by-one:
<=versus<, or starting at 1 instead of 0. - A stray semicolon:
for (int i = 0; i < 5; i++);has an empty body, so the block below runs once. - Modifying a collection while looping over it with for-each: this throws
ConcurrentModificationException(covered in the collections lessons).
What's next#
You can now repeat work. Next we organise code into reusable, named building blocks: methods.
Check your understanding
Quick quiz
1.How many times does the body of
for (int i = 0; i < 10; i += 3)run?2.Which loop always runs its body at least once?
3.Inside nested loops, what does
continuedo?
Finished reading?
Mark this lesson complete to track your progress.