Java while Loop
Table of Contents + β
In the last lesson you learned about the Java for loop. A for loop is great when you know the count ahead of time. But sometimes you do not.
Think of βkeep asking for the password until it is correct.β For repeats like that, Java gives you the while loop.
π€ When for is not enough
A for loop suits a known count. Many real jobs are open-ended, so you only know when to stop:
- Keep reading numbers until the user enters 0.
- Keep playing rounds until the player runs out of lives.
- Keep retrying a connection until it succeeds.
- Keep asking for a valid age until they give one.
The number of repeats depends on what happens while the program runs, so you cannot know it in advance. What you do know is the condition to keep going. A while loop repeats as long as that condition stays true.
A for loop is like a staircase with a known number of steps. A while loop is like driving while the light is green, and stopping the moment it turns red.
π§© The while loop syntax
A while loop is just a condition and a body, with no init or update section built in:
while (condition) { // this body repeats as long as the condition is true}How it runs:
- Java checks the
conditionbefore each pass, never after. - If it is
true, the body runs once, then Java checks again. - If the condition is already false at the start, the body never runs, not even once.
- A
forhasi++built into its brackets; awhiledoes not, so you must change something in the body or it never ends.
Here is βcount to 5β as a while loop, to compare with the for version.
int i = 1; // start value, set BEFORE the loopwhile (i <= 5) { // condition checked before each pass System.out.println(i); i++; // update, INSIDE the body, this is on you}The three pieces are now spread across three places:
- The counter
iis created before the loop. - The condition
i <= 5sits inside the brackets. - The update
i++lives inside the body. - Java stops when
ibecomes 6, because6 <= 5is false.
Output
12345A for loop reads better for a fixed count like this. Next is a job a for loop cannot do cleanly.
π― A loop that really needs while
The real strength of while is repeating an unknown number of times, controlled at runtime. A common pattern is reading input until the user types a special stop value. That stop value is called a sentinel: an agreed signal meaning βIβm done.β
Letβs add up numbers from the user and stop when they type 0. So 0 is our sentinel.
import java.util.Scanner;
public class SumUntilZero { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int total = 0;
System.out.print("Enter a number (0 to stop): "); int number = scanner.nextInt(); // read the FIRST number before the loop
while (number != 0) { // keep going until they type 0 total = total + number; // add this number to the running total System.out.print("Enter a number (0 to stop): "); number = scanner.nextInt(); // read the NEXT number, this updates the condition }
System.out.println("The total is " + total); }}The order matters here:
- We read one number before the loop, so the first check has a value to look at.
- The condition
number != 0reads as βwhile the number is not zero, keep going.β - Inside, we add the number to
total, then read the next number. - That second read updates
number, the exact thing the condition checks, so each pass moves closer to stopping. - When the user types 0, the condition becomes false and the loop ends. The 0 is never added, because it never enters the body.
A for loop cannot do this cleanly. We never know how many numbers the user will type, and while is built for exactly that.
Output
Enter a number (0 to stop): 10Enter a number (0 to stop): 20Enter a number (0 to stop): 5Enter a number (0 to stop): 0The total is 35The 0 was just the signal to stop. The total is 10 + 20 + 5, which is 35.
π Leaving a loop early with break
To stop a loop in the middle, before the condition naturally becomes false, use the break statement. When Java hits break, it jumps straight out of the loop no matter what the condition says.
Here is a password retry: keep asking, but stop the instant the answer is correct.
import java.util.Scanner;
public class PasswordCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
while (true) { // loops forever ON PURPOSE System.out.print("Enter password: "); String entered = scanner.nextLine();
if (entered.equals("java123")) { System.out.println("Access granted!"); break; // β
correct password, leave the loop now }
System.out.println("Wrong, try again."); } }}Reading while (true):
- The condition is always true, so on its own the loop would never end. That is on purpose.
- The real exit is the
breakinside theif. - When the password matches,
breakfires and we leave the loop straight away. - This is clean when the natural stopping point lives in the middle of the body, not at the top.
Output
Enter password: helloWrong, try again.Enter password: java123Access granted!while (true) is only safe because of a clear break that you know will run. With no reachable break, you have an infinite loop, which is the next danger.
β οΈ The infinite loop danger
If the condition never becomes false, the loop runs forever and your program freezes. This almost always happens because you forgot to change the thing the condition checks.
Here is count-to-5 with the update removed.
int i = 1;// β Bad: i never changes, so i <= 5 is always true, foreverwhile (i <= 5) { System.out.println(i); // forgot i++ β nothing moves i toward 6}Without i++, i stays 1 forever, so i <= 5 is always true and the loop never stops. The screen fills with 1 until you force-quit.
The fix is one line.
int i = 1;// β
Good: i grows each pass, so the loop reaches its endwhile (i <= 5) { System.out.println(i); i++; // this is what eventually makes the condition false}The rule: inside every while loop, something must change so the condition will eventually become false.
Always move toward the exit
Inside every while loop, something must change so the condition will one day become false. A counter that grows. A value the user types. A flag that flips. If nothing changes, the loop runs forever and the program freezes.
π while vs for: which to use
Ask one question: do I know the number of repeats before the loop runs?
- Use
forwhen you know the count up front: counting, a fixed range, or doing something exactly N times. The counter and limit sit in the brackets, making intent obvious. - Use
whilewhen you know only the condition to keep going: reading until a sentinel, retrying until success, or looping until the user quits. - Either can solve the otherβs problem, but each reads more naturally in its own situation, so pick the one that matches what you know when you write the code.
β οΈ Common Mistakes
A few while slip-ups that trip up almost everyone at first.
- Forgetting to update the condition variable. If nothing in the body changes what the condition checks, you get an infinite loop.
// β Wrong: count never changes, loop never endsint count = 0;while (count < 3) { System.out.println("Hi");}
// β
Right: count grows, loop ends after 3 printsint count = 0;while (count < 3) { System.out.println("Hi"); count++;}- Checking the wrong variable. Make sure the thing you change inside the loop is the same thing the condition checks. Updating a different variable will not stop the loop.
// β Wrong: condition checks i, but we update j, so i never movesint i = 0;int j = 0;while (i < 5) { System.out.println(i); j++; // wrong variable! i is still 0}
// β
Right: update the SAME variable the condition checksint i = 0;while (i < 5) { System.out.println(i); i++;}- Getting the start or limit wrong, an off-by-one error. A small mistake in the start value or the comparison can run one time too many or one time too few. Always double-check the boundary.
// β Off by one: prints 1 to 5, but we wanted 1 to 5 inclusive... this gives 1 to 4int n = 1;while (n < 5) { System.out.println(n); n++;}
// β
Use <= when you want to include 5int n = 1;while (n <= 5) { System.out.println(n); n++;}- Forgetting that the body may not run at all. A
whilechecks the condition first, so if it is false from the start, the body never runs once. Sometimes that is what you want, just make sure it is what you meant.
β Best Practices
Habits for safe, readable while loops:
- Use while for unknown counts. When you only know the stopping condition,
whileis the natural fit. If the count is known, preferfor. - Guarantee an exit. Make sure something in the body moves the condition toward false on every pass. This is the single most important habit.
- Initialize before the loop. Set up your counter or flag before the
while, sincewhilehas no init section of its own. - Keep the condition simple. A short, clear condition makes it easy to see when the loop ends. If the condition gets long, give it a well-named boolean variable.
- Use break for a mid-body exit. When the natural stopping point is in the middle of the body, a clean
breakis clearer than twisting the condition.
π§© What Youβve Learned
Letβs recap the main ideas.
- β A while loop repeats as long as its condition stays true, for an unknown number of times.
- β It checks the condition before each pass, so the body may run zero times if the condition starts false.
- β Its three pieces are spread out: init before, condition in the brackets, update inside the body.
- β It shines when you know the stopping condition but not the count, like reading until a sentinel value such as 0.
- β
break lets you leave a loop early, even out of a
while (true). - β Forgetting to update the condition variable causes an infinite loop that freezes the program.
- β Use for for known counts and while for unknown counts.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
When is a while loop a better choice than a for loop?
Why: while is ideal when you do not know the number of repeats up front, only the condition to continue.
- 2
Where does the counter update (like i++) go in a while loop?
Why: A while loop has no update section, so you must change the counter inside the body yourself.
- 3
What causes an infinite while loop?
Why: If nothing in the body moves the condition toward false, it stays true forever and the loop never ends.
- 4
If a while condition is false before the loop starts, what happens?
Why: while checks the condition first, so if it is false from the start, the body never runs even once.
π Whatβs Next?
A while loop checks the condition before running. But what if you want the body to run at least once, then check? For that there is a close cousin: the do-while loop. Letβs see how it differs.