Loops repeat a block of code. Java has four: the counting for loop, the while loop, the do-while loop that always runs at least once, and the enhanced for (for-each) loop for arrays and collections. This lesson shows each one, plus break, continue, nested loops and labelled breaks.
In this lesson you will learn
- The three parts of a
forloop - When to use
whileanddo-while - How the enhanced for loop works
- How
breakandcontinuechange the flow - Nested loops and labelled
break
The Four Loops
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.print(i * i + " ");
}
System.out.println();
int n = 40721, sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println("Digit sum: " + sum);
int tries = 0;
do {
tries++;
} while (tries < 3);
System.out.println("Tries: " + tries);
String[] cities = {"Dhaka", "Sylhet", "Khulna"};
for (String city : cities) {
System.out.println(city);
}
}
}
Output
1 4 9 16 25
Digit sum: 14
Tries: 3
Dhaka
Sylhet
Khulna
for (init; condition; update): set up a counter, keep looping while the condition is true, and update after every pass. Best when you know the count.while (condition): checks first and may run zero times. Best when you loop until something happens, like running out of digits.do { } while (condition);checks after the body, so it always runs at least once. Note the semicolon at the end.for (String city : cities): the enhanced for loop visits every element without an index. Read it as “for each city in cities”.
break, continue, Nesting and Labels
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
System.out.print(i + " ");
}
System.out.println();
for (int row = 1; row <= 3; row++) { // nested loop
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.println();
}
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i * j == 4) {
System.out.println("Found 4 at i=" + i + ", j=" + j);
break outer; // leaves both loops
}
}
}
}
}
Output
1 3 5 7
*
**
***
Found 4 at i=2, j=2
continueskips the rest of the current pass, so even numbers are not printed.breakleaves the loop completely; nothing after 7 prints.- In a nested loop, the inner loop runs fully for every pass of the outer loop, which is how the triangle of stars is drawn.
- A plain
breakonly leaves the innermost loop. A label (outer:) withbreak outer;leaves both at once.
Which Loop Should I Use?
| Loop | Use when |
|---|---|
for | You know how many times to repeat, or need the index |
enhanced for | You want every element of an array or collection |
while | You repeat until a condition changes |
do-while | The body must run at least once, such as showing a menu |
Common Mistakes
- Off-by-one errors.
i <= arr.lengthgoes one past the end; usei < arr.length. - Infinite loops when the condition’s variable is never updated.
- Changing a collection inside a for-each loop, which throws
ConcurrentModificationException. - A semicolon after
for (...), which makes the loop body empty.
Practice Exercises
Exercise 1. Print the 9 times table up to 9 × 10.
Show answer
for (int i = 1; i <= 10; i++) {
System.out.println("9 x " + i + " = " + 9 * i);
}
Exercise 2. Reverse the number 1234 using a while loop.
Show answer
int n = 1234, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println(rev); // 4321
Frequently Asked Questions
Can I get the index in an enhanced for loop?
No. Use a normal for loop when you need the position.
What is the difference between while and do-while?
while checks the condition before the first pass and may never run. do-while checks after, so it always runs at least once.
Summary
forcounts,whilerepeats until a condition changes,do-whileruns at least once.- The enhanced for loop visits every element.
breakexits,continueskips one pass, and labels exit nested loops.
Next: Java Arrays.
