Thuta Learning
Java
BasicProgrammingBeginner

Loops (For, While)

JavaLesson 1130 min

What you'll walk away with

  • Trace when the initialization, condition and update parts of a for loop run
  • Choose for when the count is known, while when only a condition is known, and do-while when the body must run at least once
  • Stop or skip iterations early with break, continue and labeled break
  • Find and fix off-by-one errors (< versus <=) and infinite loops caused by a missing update

Explain it simply

Explain it simply

A loop is an instruction to repeat a piece of work. It is like running laps around a track: if the coach says "run 5 laps", you count laps (a for loop); if the coach says "run until you are tired", you ask "am I tired yet?" before every lap (a while loop).

Without loops, printing 100 products would take 100 lines of code. With a loop it takes about three, and the code does not change even when there are ten thousand products.

Problem → Why → Solution

The problem: the program never stops

The code below should list five students and then add up the numbers 1 to 5 for a report. The first loop prints one student too many, and the second loop never stops at all, keeping the CPU busy at 100%. There is no compile error, so you only find out when the program runs.

Main.java
public class Main {
  public static void main(String[] args) {
    int students = 5;
    for (int i = 0; i <= students; i++) {     // runs 6 times: 0..5
      System.out.println("Student #" + i);
    }

    int n = 1;
    int sum = 0;
    while (n <= 5) {
      sum += n;                               // n never changes
    }
    System.out.println("Sum: " + sum);         // never reached
  }
}

Why does this happen?

The first loop starts at 0 and uses <=, so it runs six times for 0, 1, 2, 3, 4 and 5: an off-by-one error. Starting at 0 calls for < students, starting at 1 for <= students. In the second loop, the condition n <= 5 stays true forever because nothing changes n. Every while loop needs a statement (here n++) that eventually makes its condition false.

Core concept: condition, body, update

Every loop has three parts: a condition that decides whether to continue, a body that repeats, and an update that eventually makes the condition false. In for (int i = 1; i <= 5; i++), int i = 1 runs exactly once. Then i <= 5 is tested; if true, the body runs, then i++ runs and the condition is tested again. As soon as the condition is false, execution continues below the loop. An i declared in the for header exists only inside the loop.

text
for (init; condition; update) { body }
--------------------------------------
   init (once)
       |
       v
  +-> condition --false--> code after the loop
  |     | true
  |     v
  |   body
  |     |
  |     v
  +-- update

while (condition) { ... } tests the condition before the body, so if it is false from the start the body never runs. do { ... } while (condition); runs the body first and tests afterwards, so it always runs at least once, which suits showing a menu and then asking whether to continue. When you only need to read every item of an array or list, the enhanced for loop (for (String c : courses)) needs no index and so cannot be off by one; the next lesson uses it with arrays.

break stops the loop immediately and jumps below it. continue skips the rest of the current round and moves to the next one; in a for loop the update (i++) still runs before the condition is tested. In nested loops, break only stops the innermost loop, so to leave both you label the outer loop, as in outer:, and write break outer;.

To check a loop, use a trace table: columns for the round number, the value of i, the condition's result and the accumulator, filled in one round at a time. Trying three situations, zero rounds, exactly one round and many rounds, catches most loop bugs before you even run the code.

Mental model: trace one round at a time
  1. Test the condition; false means exit
  2. Run the body (watch continue/break)
  3. Run the update (i++, n--)
  4. Go back to the condition

Writing the value of i for each round on paper exposes off-by-one bugs almost instantly.

General pattern

java
for (int i = start; i < end; i++) { /* known number of rounds */ }

while (condition) { /* update something the condition uses */ }

do { /* runs at least once */ } while (condition);

for (Type item : collection) { /* every item, no index */ }

break;     // leave the loop now
continue;  // skip to the next round

Pick for when you know the number of rounds, while when you only know the condition, do-while when the body must run at least once, and the enhanced for to read every item. Note the semicolon at the end of a do-while.

Example: counting, a countdown and a running total

This example has three loops: a for loop counting 1 to 5, a while loop counting down from 3, and a loop that adds odd numbers using continue and break. The last one is the accumulator pattern: total starts at 0 outside the loop and grows each round.

Main.java
public class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
      System.out.println("For loop item: " + i);
    }

    int countdown = 3;
    while (countdown > 0) {
      System.out.println("Countdown: " + countdown);
      countdown--;
    }

    int total = 0;
    for (int n = 1; n <= 10; n++) {
      if (n % 2 == 0) continue;   // skip even numbers
      if (n > 7) break;           // stop the loop early
      total += n;
    }
    System.out.println("Sum of odd numbers up to 7: " + total);
  }
}

Code breakdown

  1. Line 3for (int i = 1; i <= 5; i++) {

    It starts at 1 and uses <= 5, so it runs five times. When i becomes 6 the condition is false and the loop ends.

  2. Lines 8-11countdown--;

    while tests countdown > 0 first, and countdown-- inside the body is what eventually makes that condition false. Without this line the loop would never end.

  3. Line 13int total = 0;

    The accumulator must be declared outside the loop. Declared inside, it would reset to 0 every round and would not exist after the loop.

  4. Line 15if (n % 2 == 0) continue; // skip even numbers

    For an even n, the rest of the body is skipped and execution jumps to n++. So total += n only runs for odd numbers.

  5. Line 16if (n > 7) break; // stop the loop early

    When n reaches 9 the loop stops at once, so the total is 1 + 3 + 5 + 7 = 16 without waiting for n <= 10 to fail.

You should see
For loop item: 1
For loop item: 2
For loop item: 3
For loop item: 4
For loop item: 5
Countdown: 3
Countdown: 2
Countdown: 1
Sum of odd numbers up to 7: 16

do-while, labeled break and the enhanced for

In the code below n is 0, so the condition n > 0 is false, yet do-while runs its body once before checking. In the nested loops, break outer; leaves both loops as soon as the first pair with i * j == 12 (3 x 4) is found; without the label only the inner loop would stop, and the search would go on to find 4 x 3 too. The last loop is an enhanced for.

Main.java
public class Main {
  public static void main(String[] args) {
    int n = 0;
    do {
      System.out.println("do-while body runs once, n = " + n);
    } while (n > 0);

    outer:
    for (int i = 1; i <= 5; i++) {
      for (int j = 1; j <= 5; j++) {
        if (i * j == 12) {
          System.out.println("Found " + i + " x " + j + " = 12");
          break outer;
        }
      }
    }

    for (String course : new String[] {"HTML", "CSS", "Java"}) {
      System.out.println("Course: " + course);
    }
  }
}

In real projects

Where this shows up in real projects

Totalling order rows from a database, sending a notification to each user in a list, and reading a CSV file line by line with while ((line = reader.readLine()) != null) are everyday loop jobs. Retry logic for a failing network call is a loop as well, but without a limit such as attempt < 3, the app keeps retrying forever while the server is down.

Modern Java often expresses filtering, mapping and summing a whole collection with the Stream API from a later lesson. Streams still run loops underneath, though, so a solid grasp of loops makes them far easier to debug. In performance-sensitive code such as game loops and data processing, the plain for loop is still everywhere.

Common mistakes

Common mistakes

1. Off-by-one: mixing up < and <=

A loop that starts at 0 with i <= count runs once too often, and on an array that means an ArrayIndexOutOfBoundsException. Make it a rule: start at 0 with i < count, or start at 1 with i <= count. Always check the value of i in the first and the last round.

2. A missing update causes an infinite loop

If nothing in a while loop changes the condition (n++, balance += ...), the loop never ends. A while loop that calls continue before its update has the same problem, because the update gets skipped. For every loop, ask which statement will eventually make the condition false.

3. Changing a list inside an enhanced for

Calling list.remove(s) inside for (String s : list) usually makes collections such as ArrayList throw a ConcurrentModificationException. To remove items use list.removeIf(...) or an Iterator's remove(); the ArrayList lesson covers this. Assigning a new value to the loop variable s does not change the item in the list either.

Mini challenge

Mini challenge: three kinds of loops

Write three tasks in one program: a row of the 7 times table, the number of months to reach a savings goal, and a sum with two conditions.

  • Print 7 x 1 through 7 x 5 with a for loop
  • With a while loop, find how many months it takes to reach 100000 starting from 20000 and saving 15000 a month
  • Add up the multiples of 3 from 1 to 100, skipping multiples of 5 with continue
  • No infinite loops and no off-by-one errors
Main.java
public class Main {
  public static void main(String[] args) {
    // 1. TODO: for loop printing "7 x i = result" for i = 1..5

    // 2. TODO: while loop; count the months until balance >= 100000
    int balance = 20000;
    int months = 0;

    // 3. TODO: for loop over 1..100 with continue; print "Sum: ..."
  }
}

Expected: The program prints these seven lines: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 Goal reached after 6 months: 110000 Sum: 1368

Show hint

In task 2 the condition is balance < 100000, and the body must update both balance and months. In task 3, continue when n % 3 != 0 || n % 5 == 0.

Show solution
Main.java
public class Main {
  public static void main(String[] args) {
    // 1. Multiplication table row
    for (int i = 1; i <= 5; i++) {
      System.out.println("7 x " + i + " = " + (7 * i));
    }

    // 2. Months until the savings goal
    int balance = 20000;
    int months = 0;
    while (balance < 100000) {
      balance += 15000;
      months++;
    }
    System.out.println("Goal reached after " + months + " months: " + balance);

    // 3. Sum of multiples of 3 from 1 to 100, skipping multiples of 5
    int sum = 0;
    for (int n = 1; n <= 100; n++) {
      if (n % 3 != 0 || n % 5 == 0) {
        continue;
      }
      sum += n;
    }
    System.out.println("Sum: " + sum);
  }
}

Quick quiz 1 / 3

What does for (int i = 0; i <= 4; i += 2) { System.out.print(i + " "); } print?

Quick quiz 2 / 3

Starting from n = 10, how many times does each body run: while (n < 5) { n++; } versus do { n++; } while (n < 5);?

Quick quiz 3 / 3

What does a plain break; (no label) inside the inner of two nested loops do?

What to remember

  • Every loop has a condition, a body and an update; without the update it never ends.
  • Use for for a known count, while for a condition, do-while for at least one run, and the enhanced for to read every item.
  • Start at 0 with i < count or at 1 with i <= count, and always check the first and last rounds.
  • break stops the loop, continue skips to the next round, and a labeled break leaves nested loops.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Loops (For, While) | Thuta Learning