The while loop
- Java course
- Beginner
- Lesson 43/116
- 4 min
Learn conditional loops with while.
The while loop
The while loop runs while a condition is true. The condition is tested at the start of each turn; when it becomes false, the loop ends.
int count = 0;
while (count < 3) {
System.out.println(count);
count++;
}Here count 0, 1, 2 is printed. The count++ line is crucial; without it the condition never becomes false and the loop runs forever. while is preferred over for when the number of iterations is not known in advance.
Infinite loop danger
Forgetting the step that makes the condition false is a common mistake. It causes an infinite loop:
int n = 0;
while (n < 5) {
System.out.println(n);
// n++ forgotten! Infinite loop.
}To avoid this, make sure the body changes something the condition depends on. You can also exit a loop with break, which we will see in the next lesson.
Practice Count down 5 to 1
Write a Main class with a main method. Assign 5 to int n. With while (n > 0) print System.out.println(n) each turn and decrement with n--.
Sample solution
public class Main {
public static void main(String[] args) {
int n = 5;
while (n > 0) {
System.out.println(n);
n--;
}
}
}Expected output
5 4 3 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the while loop
int n = 5;
while (n ____ 0) {
System.out.println(n);
n--;
}
int n = 5;
while (n > 0) {
System.out.println(n);
n--;
}
Explanation: n > 0 loops from 5 down to 1.
2 When is the condition tested in a while loop?
- At the end of the loop
- Never tested
- Only on the first turn
- At the start of each turn Correct answer
Explanation: The while condition is tested at the start of each turn.
3 Match the while concepts
| Term | Meaning |
|---|---|
while |
Loop |
(n > 0) |
Condition |
n-- |
Decrement |
{ } |
Block |