Java while Loop

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 condition before 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 for has i++ built into its brackets; a while does 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 loop
while (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 i is created before the loop.
  • The condition i <= 5 sits inside the brackets.
  • The update i++ lives inside the body.
  • Java stops when i becomes 6, because 6 <= 5 is false.

Output

1
2
3
4
5

A 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 != 0 reads 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): 10
Enter a number (0 to stop): 20
Enter a number (0 to stop): 5
Enter a number (0 to stop): 0
The total is 35

The 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 break inside the if.
  • When the password matches, break fires 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: hello
Wrong, try again.
Enter password: java123
Access 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, forever
while (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 end
while (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 for when 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 while when 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 ends
int count = 0;
while (count < 3) {
System.out.println("Hi");
}
// βœ… Right: count grows, loop ends after 3 prints
int 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 moves
int 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 checks
int 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 4
int n = 1;
while (n < 5) {
System.out.println(n);
n++;
}
// βœ… Use <= when you want to include 5
int n = 1;
while (n <= 5) {
System.out.println(n);
n++;
}
  • Forgetting that the body may not run at all. A while checks 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, while is the natural fit. If the count is known, prefer for.
  • 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, since while has 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 break is 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. 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. 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. 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. 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.

Java do-while Loop

Share & Connect