Loops in Java: for, while, do-while and the Enhanced for Loop

admin5 min read
In this tutorial
  1. The for loop
  2. The while loop
  3. The do-while loop
  4. The enhanced for loop (for-each)
  5. break and continue
  6. Nested loops
  7. Which loop should I use?
  8. Common loop bugs
  9. Practice
  10. Summary

Computers are good at doing the same thing many times without getting bored. Loops are how you tell Java to repeat work: print every item in a list, retry a network call, add up a column of numbers.

Java has four loop forms. This tutorial explains each one, when to choose it, and the bugs to watch out for.

The for loop

Use a classic for loop when you know how many times you want to repeat something, or you need the index:

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

The header has three parts separated by semicolons:

  1. Initialisation (int i = 1) runs once, before the loop starts.
  2. Condition (i <= 5) is checked before every iteration. The loop stops when it is false.
  3. Update (i++) runs after every iteration.

You can count down or step by more than one:

for (int i = 10; i > 0; i -= 2) {
    System.out.print(i + " "); // 10 8 6 4 2
}

The while loop

Use while when you do not know in advance how many iterations you need; you just know the condition for continuing:

int balance = 1000;
int months = 0;
while (balance < 2000) {
    balance += balance * 10 / 100; // 10% growth per month
    months++;
}
System.out.println("Doubled after " + months + " months");

If the condition is false at the start, the body never runs.

The do-while loop

do-while checks its condition at the end, so the body always runs at least once. It is a natural fit for menus and input validation:

import java.util.Scanner;

public class Menu {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int choice;
        do {
            System.out.println("1) Balance  2) Transfer  0) Exit");
            choice = in.nextInt();
        } while (choice != 0);
        System.out.println("Goodbye");
    }
}

Note the semicolon after while (...). It is required in a do-while.

The enhanced for loop (for-each)

When you just want every element of an array or collection, the enhanced for loop is the cleanest option:

String[] languages = {"Java", "Kotlin", "Scala"};
for (String lang : languages) {
    System.out.println(lang);
}

Read it as “for each lang in languages“. You do not manage an index, so there is no chance of an off-by-one error. The trade-off: you cannot see the index, and you cannot safely remove items from a collection while looping over it this way.

break and continue

  • break exits the loop immediately.
  • continue skips the rest of the current iteration and moves to the next one.
public class FindFirstNegative {
    public static void main(String[] args) {
        int[] readings = {12, 7, 0, -3, 15, -8};

        int sumOfPositives = 0;
        for (int r : readings) {
            if (r <= 0) {
                continue; // skip zero and negatives
            }
            sumOfPositives += r;
        }
        System.out.println("Sum of positives: " + sumOfPositives); // 34

        int firstNegativeIndex = -1;
        for (int i = 0; i < readings.length; i++) {
            if (readings[i] < 0) {
                firstNegativeIndex = i;
                break; // no need to look further
            }
        }
        System.out.println("First negative at index " + firstNegativeIndex); // 3
    }
}

Labelled break for nested loops

A plain break only exits the innermost loop. To exit an outer loop, label it:

search:
for (int row = 0; row < grid.length; row++) {
    for (int col = 0; col < grid[row].length; col++) {
        if (grid[row][col] == target) {
            System.out.println("Found at " + row + "," + col);
            break search;
        }
    }
}

Use labels sparingly. Often it is cleaner to move the nested loop into its own method and return when you find the answer.

Nested loops

Loops inside loops are common for grids, tables and comparing every pair of items:

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print(i * j + "\t");
    }
    System.out.println();
}

Output:

1   2   3
2   4   6
3   6   9

Be aware of the cost: two nested loops over n items do about n × n steps. For 10 items that is nothing; for a million items it is a trillion steps.

Which loop should I use?

  • Enhanced for: you need every element, and not the index. Your default for collections.
  • for: you need the index, a custom step, or a fixed number of repetitions.
  • while: you repeat until something happens, and the number of steps is unknown.
  • do-while: like while, but the body must run at least once.
  • Streams (list.forEach, stream().filter(...)) are another option for collections. See Java Streams for beginners.

Common loop bugs

Off-by-one errors

Arrays start at index 0, so the last valid index is length - 1:

int[] nums = {1, 2, 3};
for (int i = 0; i <= nums.length; i++) { // bug: <= should be <
    System.out.println(nums[i]);         // ArrayIndexOutOfBoundsException at i = 3
}

Infinite loops

If the condition never becomes false, the loop runs forever:

int i = 0;
while (i < 10) {
    System.out.println(i);
    // forgot i++
}

When a program seems to hang, check that every loop updates the variable in its condition.

Modifying a list while iterating

Removing items inside an enhanced for loop throws ConcurrentModificationException. Use removeIf instead:

names.removeIf(name -> name.isBlank());

Practice

  1. Print the multiplication table for any number from 1 to 12.
  2. Sum all even numbers between 1 and 100 using continue.
  3. Keep asking the user for a PIN until they enter 1234, using do-while.
  4. Find the largest number in an array without sorting it.

Summary

  • for for counted loops, while for open-ended ones, do-while when the body must run once, and enhanced for for walking through collections.
  • break exits a loop; continue skips to the next iteration.
  • Watch out for off-by-one errors, missing updates and modifying a collection mid-loop.

Next: organise your code into reusable pieces with methods in Java.

Ask a question or leave a comment

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