Loops in Java Tutorial: for, while, do-while and Worked Examples

Build one reliable control-flow model for every Java loop. Trace runnable examples, avoid boundary and update errors, and practise counting executions.

KnowledgeGate Team

Exam prep & CS education

Updated 15 Sep 20266 min read

A beginner can often read a loop but still lose track of when its condition runs, whether its update happens after continue, or why an array loop fails on the last pass. A single control-flow model applies to for, while, do-while, enhanced for, nested loops, break and continue. No loop form is universally faster than another.

What a loop does and which Java loop to choose

A loop repeats code under the control of a condition. Always trace four questions: What is the initial state? When is the condition checked? What changes in the body? What update prepares the next check?

Situation

Natural choice

Counter or range is known

for

Repeat while a changing condition remains true

while

Body must run at least once

do-while

Visit every array or Iterable value without its index

Enhanced for

These forms overlap, so choose the clearest one. With int[] scores = {72, 85, 91, 68};, an index-based for suits a task in which position matters. for (int score : scores) suits a task needing only the values.

Build wider syntax and type knowledge through a Java programming foundation. The Coding & Skills path provides broader context.

The Java for loop, traced from start to finish

In for (initialisation; condition; update), initialisation runs once. Java checks the condition, runs the body if true, performs the update, and checks again. A false first check means zero body executions.

java
int sum = 0;

for (int i = 1; i <= 5; i++) {
    sum += i;
    System.out.println("i=" + i + ", sum=" + sum);
}

System.out.println("Final sum=" + sum);

The body prints i=1, sum=1, i=2, sum=3, i=3, sum=6, i=4, sum=10, and i=5, sum=15. The last line is Final sum=15.

i before body

condition i <= 5

sum after body

i after update

1

true

1

2

2

true

3

3

3

true

6

4

4

true

10

5

5

true

15

6

6

false

body not run

no update

The failed check at i = 6 prevents a sixth execution. for (int i = 2; i <= 10; i += 2) visits 2, 4, 6, 8, 10; for (int i = 5; i >= 1; i--) visits 5, 4, 3, 2, 1. The initial value, operator and update must lead towards termination.

Flowchart of the sum loop showing i and sum advancing from (1,1) to (5,15) and the failed check at i=6.

while versus do-while with exact state changes

Use while when the number of passes is not known in advance. This example sums the digits of 482:

java
int n = 482;
int digitSum = 0;

while (n > 0) {
    int digit = n % 10;
    digitSum += digit;
    n /= 10;
}

The states (n, digit, digitSum) are (482, 2, 2), (48, 8, 10), and (4, 4, 14). Integer division then makes n equal 0, so n > 0 fails. The answer is 14.

A while loop is entry-controlled. With int attempts = 0, while (attempts > 0) { System.out.println(attempts); } prints nothing. A do-while loop is exit-controlled:

java
do {
    System.out.println(attempts);
} while (attempts > 0);

It prints 0 once. The semicolon after the condition is required. Use while to consume input while valid data remains, or do-while to show a menu once before asking whether to repeat.

Enhanced for loops and nested loops

An enhanced for gives you each value, not its index:

java
int[] marks = {64, 81, 73, 92};
int max = marks[0];

for (int mark : marks) {
    if (mark > max) max = mark;
}

max changes as 64 -> 81 -> 81 -> 92, so the result is 92. However, for (int mark : marks) { mark += 5; } does not modify the array. For primitive integers, mark is a local copy. An index loop, for (int i = 0; i < marks.length; i++) { marks[i] += 5; }, changes the array to [69, 86, 78, 97].

For a grid, let the outer loop run row = 1..3 and the inner loop run col = 1..4, printing ("(" + row + "," + col + ") "). The first row is (1,1) to (1,4), followed by (2,1) to (2,4), then (3,1) to (3,4). The outer body begins 3 times, and the inner body runs 3 x 4 = 12 times.

A 3-by-4 grid of coordinates from (1,1) to (3,4) showing the inner loop runs 12 times across three rows.

break, continue and the loop errors beginners make

Consider for (int i = 1; i <= 8; i++). First run if (i == 7) break;, then if (i % 3 == 0) continue;, then print i. The output is 1 2 4 5. Values 3 and 6 are skipped by continue. At 7, break exits the nearest enclosing loop before 7 or 8 can print. A continue only skips the rest of the current pass.

Three small mistakes cause very different failures:

  • i <= marks.length eventually tries index 4 in a four-element array. That compiles, but throws ArrayIndexOutOfBoundsException. Use i < marks.length.

  • for (int i = 1; i <= 5; i--) moves away from its stopping condition. Use i++.

  • while (count < 3); has an empty body and can remain stuck. Remove the stray semicolon and update count inside the braces.

There is another trap in while. Starting with int i = 0, if if (i == 2) continue; comes before i++, then i remains 2 forever. Update on every path, or use a for whose update expression still runs after continue. Keep compile-time errors, runtime exceptions and non-terminating logic errors separate when diagnosing a loop.

How exams and interviews test Java loops

Common tasks ask you to predict exact output, count body executions, or find a boundary or termination bug. Mark the initialisation, every condition result and every update before calculating anything.

For int value = 1; for (int i = 0; i < 4; i++) { value *= 2; }, the body runs four times and value changes 1 -> 2 -> 4 -> 8 -> 16. Changing the condition to i <= 4 gives five passes and produces 32. An index ceiling and an iteration count are related, but they are not interchangeable.

Loop counting also starts complexity analysis. One full pass over n values is commonly linear work. A full n by n loop performs n^2 body executions. Nesting alone does not prove that result when the bounds change or both loops do not span n; time complexity and asymptotic notation develops that reasoning. For practice, the site has about 50 Java questions available, covering the language more broadly than loops alone.

Practice checks, the short version and your next step

Practise with these loop-tracing exercises:

  1. Sum the values visited by for (int i = 2; i <= 10; i += 2).

  2. Run the digit loop with n = 205. Which digits are extracted, and what is their sum?

  3. Run rows 1..2 with inner columns 1..3. How many times does the inner body execute?

Answers: 2 + 4 + 6 + 8 + 10 = 30; the digits are 5, 0, 2 and their sum is 7; the nested body runs 2 x 3 = 6 times.

The short selector is simple. Use for for explicit counter control, while for condition-led repetition, do-while when one first pass is required, and enhanced for when values matter but indices do not. Every loop still needs a reachable stopping condition and boundaries based on valid indices.

Choose the next step by need. Learn the wider Java language, apply Java to data structures and interview problems, or see loops inside sorting algorithms.