while Loop in Java
The while loop in Java repeats a block of code as long as a given condition remains true. Unlike the for loop, it's best suited for situations where the number of iterations isn't known in advance.
Syntax
while (condition) {
// code to repeat
}
Basic Example
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
// prints 1 2 3 4 5
How the while Loop Works
The condition is checked before each iteration. If it's true, the loop body executes; if it's false right from the start, the loop body never runs at all — this is why while is called an entry-controlled loop.
Using while for Unknown Iteration Counts
The while loop is especially useful when reading input or processing data until a certain condition is met, such as reading lines from a file until the end is reached.
int sum = 0;
int n = 5;
while (n > 0) {
sum += n;
n--;
}
System.out.println(sum); // 15
Infinite while Loop
A while loop with a condition that's always true runs forever unless stopped with a break statement inside.
while (true) {
// runs forever unless broken out of
}
whilechecks its condition before the loop body runs (entry-controlled)- Best used when the number of iterations depends on a condition rather than a fixed count
- Forgetting to update the condition variable inside the loop causes an infinite loop
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.
Tracing a while Loop by Hand
A simple way to understand any loop is to write down the variables after each pass. This program prints the numbers 1 to 5:
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
// Output: 1 2 3 4 5
| Pass | Value of i before check | Condition i <= 5 | Printed |
|---|---|---|---|
| 1 | 1 | true | 1 |
| 2 | 2 | true | 2 |
| 3 | 3 | true | 3 |
| 4 | 4 | true | 4 |
| 5 | 5 | true | 5 |
| - | 6 | false | loop ends |
The condition is checked one extra time at the end. That final false check is what lets the program move on to the next statement.
Practical Examples You Will Actually Write
Adding the digits of a number
Here the number of passes depends on how many digits the number has, which is exactly the kind of case where while fits better than for:
int number = 4821;
int digitSum = 0;
while (number > 0) {
digitSum += number % 10; // take the last digit
number /= 10; // remove the last digit
}
System.out.println(digitSum); // 15
Reading input until the user types exit
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
while (!line.equalsIgnoreCase("exit")) {
System.out.println("You typed: " + line);
line = sc.nextLine();
}
System.out.println("Goodbye");
Inside a while loop you can also use continue to skip the rest of the current pass, and break to leave the loop early. When using continue, make sure the counter is updated before it, or the loop may never end.
while, for and do-while Compared
| Loop | Condition checked | Best for |
|---|---|---|
for | Before each pass | A known number of repetitions, such as walking through an array |
while | Before each pass | Repeating until something happens, such as end of input |
do-while | After each pass | Code that must run at least once, such as showing a menu |
Bugs Beginners Hit with while Loops
- A stray semicolon:
while (i < 5);creates an empty loop body that runs forever, and the block below runs only afterwards, if ever. - Off-by-one errors: using
<instead of<=skips the last value. Trace the first and last pass to check. - Comparing decimals exactly: a condition such as
x != 1.0with a double that increases by 0.1 may never become false because of rounding. Use<or an integer counter. - Counter declared inside the loop: it is reset on every pass, so the condition never changes.
Quick check before running: the variable in the condition is set before the loop, something inside the body changes it, and the change moves it toward making the condition false. If a program seems frozen while testing, an endless loop is the first suspect; add a temporary print statement inside the body to watch the variable change.