Java while Loop
What is a while Loop?
A while loop repeats a block of code as long as a condition stays true. Unlike a for loop, it doesn't have a built-in initialization or update section — you set up the counter (if you need one) before the loop, and update it yourself inside the loop body. This makes while loops the natural choice when you don't know in advance exactly how many times the loop will run.
Basic Syntax
while (condition) {
// code to repeat
}Java checks the condition BEFORE every iteration, including the very first one. If the condition is false right from the start, the loop body never runs at all.
A Simple Example
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Condition Checked First: Zero Runs is Possible
int count = 10;
while (count < 5) {
System.out.println("This never prints.");
count++;
}
System.out.println("Loop skipped entirely.");Loop skipped entirely.
Common Pattern: Sentinel-Controlled Loop
A sentinel value is a special value that signals "stop" instead of being real data. This pattern is common when reading a stream of input until a special marker shows up.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int total = 0;
int number = scanner.nextInt();
while (number != -1) {
total += number;
number = scanner.nextInt();
}
System.out.println("Total: " + total);Common Pattern: Input Validation
while loops are also the standard tool for re-prompting a user until they provide valid input.
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
int age = -1;
while (age < 0 || age > 120) {
System.out.print("Enter a valid age (0-120): ");
age = scanner.nextInt();
}
System.out.println("Age accepted: " + age);while vs for
Situation | Better Choice |
You know the exact number of iterations in advance | for |
You're looping until a condition becomes true/false (unknown count) | while |
You're validating input or waiting for a sentinel value | while |
You need a counter, start, and update all visible in one line | for |
Practice Exercises
Use a while loop to print numbers from 10 down to 1.
Write a while loop that keeps asking the user for a password until they enter the correct one.
Sum numbers entered by a user until they type 0.
Use a while loop to find the first power of 2 greater than 1000.