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.
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:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Lap " + i);
}
}
}Lap 1
Lap 2
Lap 3
Lap 4
Lap 5The parentheses hold three parts separated by semicolons:
- Initialization (
int i = 1): runs once, before the loop. - Condition (
i <= 5): checked before every repetition; the loop stops when it is false. - Update (
i++): runs after every repetition.
The while loop#
Use while when you repeat until something changes, without knowing in advance how many times:
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);
}
}Doubled after 8 years: 2142The 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":
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);
}
}Enter a number from 1 to 10: 15
Enter a number from 1 to 10: 7
Thanks, you chose 7Note 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:
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);
}
}
}apple
banana
cherryRead 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?#
Infinite loops#
If the condition never becomes false, the loop never ends:
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#
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();
}
}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
public class Table {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("7 x " + i + " = " + 7 * i);
}
}
}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 = 70Practice exercise
Using a while loop, count how many times 1000 can be halved (with integer division) before it reaches 0.
Show solution
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);
}
}10Key takeaway#
Finished this lesson?