Java While Loop
A loop repeats a block of code. Computers are very good at repetition: printing a thousand lines, adding up all the numbers in a list, asking again until the answer is valid. The simplest loop in Java is while: it repeats its block as long as a condition is true.
The while loop
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
System.out.println("Done, i is now " + i);
}
}Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Done, i is now 6
Step by step: the condition i <= 5 is checked first. It is true, so the block runs and i becomes 2. The condition is checked again, and so on. When i reaches 6 the condition is false and the program continues after the loop.
If you forget i++, the condition stays true for ever and the loop never ends. This is an endless loop. In our editor, press Stop to end such a program.
A loop that adds up
A common pattern keeps a running total in a variable that starts at zero:
public class Main {
public static void main(String[] args) {
int n = 1, sum = 0;
while (n <= 100) {
sum += n;
n++;
}
System.out.println("1 + 2 + ... + 100 = " + sum);
}
}1 + 2 + ... + 100 = 5050
Loops that depend on the data
A while loop is the right choice when you do not know in advance how many times it will run. This one counts how many times a number can be halved before it reaches 1:
public class Main {
public static void main(String[] args) {
int number = 1000, steps = 0;
while (number > 1) {
number /= 2;
steps++;
}
System.out.println("Halved " + steps + " times.");
}
}Halved 9 times.
do while: run at least once
A do ... while loop checks its condition after the block, so the block always runs at least once. That is perfect for asking the user 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 guess;
do {
System.out.print("Enter a number from 1 to 10: ");
guess = in.nextInt();
} while (guess < 1 || guess > 10);
System.out.println("Thank you, you chose " + guess + ".");
}
}42 0 7
Enter a number from 1 to 10: Enter a number from 1 to 10: Enter a number from 1 to 10: Thank you, you chose 7.
Notice the semicolon after the while (...) at the end. The program asked three times because 42 and 0 are outside the range. Input is read as in User Input.
When you know exactly how many times to repeat, the for loop in the next topic, For Loop, is usually shorter and clearer.
Practice exercises
- Print the numbers from 10 down to 1 with a while loop, then print "Lift off!".
- Add up the even numbers from 2 to 50 and print the total.
- Keep asking for numbers and adding them until the user enters 0; then print the total.