Reading history

Java Loops: for, while, do-while and for-each

3 min read 0 views

Learn Java loops: for, while, do-while and the enhanced for-each loop, plus break, continue, nested loops and labelled break, with examples.

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 for loop
  • When to use while and do-while
  • How the enhanced for loop works
  • How break and continue change 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
  • continue skips the rest of the current pass, so even numbers are not printed.
  • break leaves 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 break only leaves the innermost loop. A label (outer:) with break outer; leaves both at once.

Which Loop Should I Use?

LoopUse when
forYou know how many times to repeat, or need the index
enhanced forYou want every element of an array or collection
whileYou repeat until a condition changes
do-whileThe body must run at least once, such as showing a menu

Common Mistakes

  1. Off-by-one errors. i <= arr.length goes one past the end; use i < arr.length.
  2. Infinite loops when the condition’s variable is never updated.
  3. Changing a collection inside a for-each loop, which throws ConcurrentModificationException.
  4. 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

  • for counts, while repeats until a condition changes, do-while runs at least once.
  • The enhanced for loop visits every element.
  • break exits, continue skips one pass, and labels exit nested loops.

Next: Java Arrays.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *