Skip to content
Laviyx Learn

Try

Java course menu

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

An introduction to loops in Java: the for loop, the while loop, the do-while loop, the enhanced for-each loop over arrays and collections, how to choose between them, and how to avoid infinite loops and off-by-one errors.

Beginner9 min readUpdated
On this page

A loop repeats a block of code. Java has four kinds; this lesson introduces all of them, and the following lessons go deeper.

The for loop#

Use for when you are counting or know how many times to repeat:

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Lap " + i);
        }
    }
}
Output
Lap 1
Lap 2
Lap 3
Lap 4
Lap 5

The parentheses hold three parts separated by semicolons:

  1. Initialization (int i = 1): runs once, before the loop.
  2. Condition (i <= 5): checked before every repetition; the loop stops when it is false.
  3. Update (i++): runs after every repetition.

The while loop#

Use while when you repeat until something changes, without knowing in advance how many times:

Java
public class Main {
    public static void main(String[] args) {
        int balance = 1000;
        int years = 0;

        while (balance < 2000) {
            balance = balance * 110 / 100;   // 10% growth per year
            years++;
        }
        System.out.println("Doubled after " + years + " years: " + balance);
    }
}
Output
Doubled after 8 years: 2142

The condition is checked before each repetition, so the body may run zero times.

The do-while loop#

do ... while checks the condition after the body, so the body always runs at least once. It suits "ask until the answer is valid":

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int number;
        do {
            System.out.print("Enter a number from 1 to 10: ");
            number = in.nextInt();
        } while (number < 1 || number > 10);

        System.out.println("Thanks, you chose " + number);
    }
}
Output
Enter a number from 1 to 10: 15
Enter a number from 1 to 10: 7
Thanks, you chose 7

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

The enhanced for loop (for-each)#

To visit every element of an array or collection, the enhanced for loop is the simplest choice:

Java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> fruits = List.of("apple", "banana", "cherry");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}
Output
apple
banana
cherry

Read it as "for each fruit in fruits". It works with arrays and every collection, and there is no index to get wrong.

Which loop should I use?#

SituationLoop
Visit every element of an array or collectionenhanced for
Count a known number of times, or need the indexfor
Repeat while a condition holdswhile
Run at least once, then checkdo ... while

Infinite loops#

If the condition never becomes false, the loop never ends:

Java
int i = 0;
while (i < 5) {
    System.out.println(i);
    // forgot i++, so i stays 0 forever
}

Stop a runaway program with Ctrl + C in the terminal (or the stop button in your IDE), then make sure the loop moves towards its end. Intentional endless loops, such as a server's main loop, are written while (true) and left with break.

Off-by-one errors#

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) System.out.print(i + " ");
        System.out.println();
        for (int i = 0; i <= 3; i++) System.out.print(i + " ");
        System.out.println();
    }
}
Output
0 1 2 
0 1 2 3 

i < 3 runs 3 times; i <= 3 runs 4 times. For an array of length n, use i = 0; i < n.

Common mistakes#

Practice#

Practice exercise

Print the multiplication table of 7, from 7 x 1 = 7 to 7 x 10 = 70.

Show solution
Java
public class Table {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            System.out.println("7 x " + i + " = " + 7 * i);
        }
    }
}
Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Practice exercise

Using a while loop, count how many times 1000 can be halved (with integer division) before it reaches 0.

Show solution
Java
public class Halving {
    public static void main(String[] args) {
        int n = 1000;
        int steps = 0;
        while (n >= 1) {
            n /= 2;
            steps++;
        }
        System.out.println(steps);
    }
}
Output
10

Key takeaway#

Finished this lesson?