Java While Loop
A while loop is a loop that repeats its block while its condition stays true. The condition is checked before each pass.
A counter loop
The counter starts at 0. Each pass prints the counter and then adds 1 to it.
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}A countdown
The counter starts at 3 and falls by 1 on each pass. The loop stops when the counter reaches 0.
public class Main {
public static void main(String[] args) {
int i = 3;
while (i > 0) {
System.out.println(i);
i--;
}
System.out.println("Go");
}
}A do/while loop runs once
The condition here is false after the first pass. The block still runs once before that check.
public class Main {
public static void main(String[] args) {
int i = 10;
do {
System.out.println(i);
i++;
} while (i < 5);
}
}Example
public class Main {
public static void main(String[] args) {
int i = 1;
int total = 0;
while (i <= 5) {
total += i;
i++;
}
System.out.println(total);
}
}Key points
- The while keyword starts the loop.
- The condition sits in parentheses after while.
- The block repeats while the condition is true.
- A value tested by the condition must change, or the loop never stops.
- A do/while loop checks its condition after its block.
- A do/while loop always runs its block at least once.
In this example, i starts at 1 and total starts at 0. Each pass adds i to total and then adds 1 to i. The total passes through 1, 3, 6, and 10. The last pass adds 5, and the printed total is 15.
Note
A while loop runs zero times when its condition starts false.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does a do/while loop guarantee?