Java · Beginner

Loops in Java: for, while and do-while

9 min readUpdated September 24, 2026Every example verified

In short: A loop repeats a block while a condition holds. for suits a known number of steps with a counter, while repeats until something changes, and do-while runs the body at least once. break leaves a loop early and continue skips to the next iteration.

Repeating work

Most useful programs do the same thing many times: print a label for every seat, add up every reading, keep asking until the answer is valid. A loop is a block that runs repeatedly, and the three loop statements differ only in how they decide whether to go round again.

The for loop packs the bookkeeping into its header: for (int i = 1; i <= 5; i++). The first part runs once, before the loop, and usually declares a counter. The second is the condition, checked before every iteration; the loop ends when it is false. The third runs after each iteration, usually moving the counter. The counter declared in the header exists only inside the loop, which keeps it from leaking into the rest of the method.

The while loop keeps just the condition: while (reading != -1). Whatever makes the condition eventually false must happen inside the body, or the loop never ends. while fits when the number of iterations is not known in advance, such as reading values until a sentinel appears, or halving a number until it drops below a limit.

do-while checks its condition after the body, so the body runs at least once. That is the natural shape for "ask, then repeat while the answer is invalid", where you cannot test the answer before you have one.

There is also a for loop for walking a collection: for (int t : temps) visits every element of an array in order without an index. It is covered in the arrays lesson.

Two statements change the flow from inside a loop. break leaves the loop immediately, skipping any remaining iterations; it is how a search stops as soon as it finds what it wants. continue abandons the current iteration and goes straight to the next check, which reads better than wrapping the rest of the body in an if. Each applies to the innermost loop that contains it.

Loops nest. An outer loop over rows with an inner loop over columns visits every cell of a grid, and the inner loop runs to completion for every single iteration of the outer one, so three rows of four columns cost twelve iterations. Keep the total in mind: two nested loops over a thousand items each run a million times.

The classic loop bug is the off-by-one: stopping one step early or one step late. Decide whether the last value should be included and pick < or <= accordingly, then check the first and last iterations by hand. i < n runs n times starting from zero; i <= n runs n times starting from one.

Syntax

 Java · syntax
for (init; condition; update) {
    // runs while condition is true; update runs after each pass
}

while (condition) {
    // checked before every pass; may run zero times
}

do {
    // runs first, then the condition is checked
} while (condition);

break;      // leave the innermost loop now
continue;   // skip the rest of this pass and re-check the condition

while (true) with a break inside is the usual way to write a loop whose exit test sits in the middle of the body. Note the semicolon after the do-while condition.

Counting with for

Seat labels counted up, then a total counted down in steps of three.

 Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Seat " + i);
        }
        int total = 0;
        for (int i = 10; i > 0; i -= 3) {
            total += i;
        }
        System.out.println("Total: " + total);
    }
}

Output

Seat 1
Seat 2
Seat 3
Seat 4
Seat 5
Total: 22

The first loop starts at 1 and includes 5 because the condition is <=. The second visits 10, 7, 4 and 1; when i becomes -2 the condition i > 0 fails and the loop ends, so the sum is 22. Both loops may reuse the name i because each header's variable exists only inside its own loop. total is declared outside, since it must survive the loop to be printed.

while until a sentinel, and do-while

Temperature readings arrive on one line and end with -1. The program is run with the input 18 21 19 22 -1.

 Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 0;
        int sum = 0;
        int reading = in.nextInt();
        while (reading != -1) {
            sum += reading;
            count++;
            reading = in.nextInt();
        }
        System.out.println("Readings: " + count);
        System.out.println("Average: " + (double) sum / count);

        int attempts = 0;
        do {
            attempts++;
        } while (attempts < 3);
        System.out.println("Attempts: " + attempts);
    }
}

Input given to the program: 18 21 19 22 -1

Output

Readings: 4
Average: 20.0
Attempts: 3

The number of readings is unknown, so a while loop reads until the sentinel -1 appears; the sentinel itself is not added. Reading the next value at the end of the body is what eventually makes the condition false. Scanner skips whitespace, so it does not matter that the values share one line. The do-while runs its body first and then tests, so attempts reaches 3 and the loop stops.

Nested loops, continue and break

A three-by-four grid of cell labels that skips column 3, then a search that stops as soon as it succeeds.

 Java
public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 4; col++) {
                if (col == 3) {
                    continue;
                }
                System.out.print(row + "-" + col + " ");
            }
            System.out.println();
        }
        int n = 1;
        while (true) {
            n *= 2;
            if (n > 50) {
                break;
            }
        }
        System.out.println("First power of two above 50: " + n);
    }
}

Output

1-1 1-2 1-4
2-1 2-2 2-4
3-1 3-2 3-4
First power of two above 50: 64

The inner loop runs all four columns for each row; continue skips only the print for column 3 and moves to column 4. The empty println after the inner loop ends each row. The second loop has no exit condition in its header: while (true) runs until break fires, which happens the first time n exceeds 50, at 64.

Which loop to reach for

SituationLoopWhy
A known number of steps, or an indexforcounter, condition and step are visible in one line
Repeat until some state changeswhileno counter needed; may run zero times
Do something, then repeat if neededdo-whilethe body must run once before there is anything to test
Visit every element of an array or listfor (T x : items)no index to get wrong

Common mistakes

  • A semicolon straight after the loop header

    Why it goes wrong: for (int i = 0; i < 3; i++); is a complete loop with an empty body. The block that follows runs once, after the loop has finished, and the compiler does not object.

    Fix: Never put a semicolon between a for or while header and its opening brace.

     Java · fix
    for (int i = 0; i < 3; i++) {
        System.out.println(i);
    }
  • Forgetting to change what the condition tests

    Why it goes wrong: while (reading != -1) with no new read inside the body checks the same value forever; the program hangs with no error message.

    Fix: Make sure every path through the body moves toward the exit: read the next value, decrement the counter, or break.

  • Off-by-one in the condition

    Why it goes wrong: for (int i = 1; i < n; i++) was meant to count to n but stops at n-1; i <= size on an index runs one step too far.

    Fix: Decide whether the last value is included, then check the first and last iterations by hand before running.

  • Using the counter after the loop

    Why it goes wrong: A variable declared in a for header exists only inside that loop; System.out.println(i) afterwards fails with cannot find symbol.

    Fix: Declare the variable before the loop when its final value is needed later.

     Java · fix
    int i = 0;
    while (i < 3) {
        i++;
    }
    System.out.println(i);

Where you use this

Processing a stream of input is the everyday loop: read a line, handle it, repeat until there is nothing left. Scanner offers hasNextInt() and hasNextLine() for exactly this, so the loop needs no sentinel and no count in advance. A billing job walks every invoice, a log analyser walks every line and a game loop walks every frame in the same way. Retry logic is the other common shape: attempt an operation, and while it failed and attempts remain, wait and try again, which is a while with a counter and a break on success.

 Java · in practice
Scanner in = new Scanner(System.in);
int sum = 0;
int count = 0;
while (in.hasNextInt()) {
    sum += in.nextInt();
    count++;
}
System.out.println(count + " values, sum " + sum);

Key points

  • for (init; condition; update) is for counted loops; the header variable is scoped to the loop.
  • while tests before each pass and may run zero times; do-while tests after and runs at least once.
  • Something in the body must eventually make the condition false, or the loop never ends.
  • break exits the innermost loop; continue jumps to the next iteration.
  • In nested loops the inner loop runs to completion for every outer iteration.
  • Check the first and last iteration by hand to catch off-by-one errors.
  • Reading input with hasNextInt() or hasNextLine() needs no sentinel.

Try it yourself

The program counts down from 5 to 1 and then prints Go. Change it to read a number n from input and count down from n to 1 instead, still printing Go at the end.

Your program
public class Main {
    public static void main(String[] args) {
        for (int i = 5; i >= 1; i--) {
            System.out.println(i);
        }
        System.out.println("Go");
    }
}
Input the program receives: 3
Expected output: 3 2 1 Go

Practise this

Exercises for this lesson are in the Java practice set.

Open the Java playground

Frequently asked questions

When should I use while instead of for in Java?

Use for when you know how many times to repeat or you are stepping an index, because the counter, condition and step sit together in the header. Use while when the loop ends because of something that happens inside it, such as reaching the end of the input or a value crossing a threshold. Any loop can be written either way; choose the one that makes the exit condition obvious.

What is the difference between break and continue?

break ends the loop entirely and execution continues after it. continue ends only the current pass: the rest of the body is skipped, the update and condition run, and the loop carries on. Both act on the innermost loop containing them.

Progress is stored only in this browser.

How this page was checked. Every program on it was run with OpenJDK 21 at build time by the publishing checks, and the output shown is what it printed. Running Java inside the browser is not available yet, so the Run button is absent rather than pretending; copy the code and run it with OpenJDK 21 locally.