PartWhere it livesExamplePurpose
InitializationBefore the loopint day = 1;Gives the condition something to test
ConditionIn the parenthesesday <= 4true runs the body; false exits
UpdateInside the bodyday++;Moves the state toward false

Rules worth remembering:

  1. The condition must be boolean (or Boolean). while (n) with an int does not compile.
  2. There is no semicolon after while (condition). Adding one creates an empty loop body.
  3. Always use braces, even for a one-line body.

How Does a While Loop Work in Java?

Whiteboard
Loading diagram...

Java tests the condition first. Each time the body finishes, control jumps back to the test, and the loop ends the first time the test is false.

While Loop Examples in Java

Example 1: A Simple Counter

Code (Java 21):

Output:

Day 1: practise JavaDay 2: practise Java
Day 3: practise Java
Day 4: practise Java
Week plan ready

Dry Run of Example 1

Checkdayday <= 4What happens
11trueprints “Day 1…”, day becomes 2
22trueprints “Day 2…”, day becomes 3
33trueprints “Day 3…”, day becomes 4
44trueprints “Day 4…”, day becomes 5
55falseloop ends; “Week plan ready” is printed

The condition was tested 5 times and the body ran 4 times. A counter like this works fine in a while loop, but a for loop puts all three parts in one line, which is cleaner when the count is known. The real strength of while shows in the next examples.

Can a While Loop Run Zero Times in Java?

Yes. If the condition is false on the first check, the body is skipped entirely.

Code (Java 21):

Output:

 Inbox is clear

That is exactly what you want for “nothing to do” cases: no special if check is needed before the loop.

Example 2: Sum of Digits Using a While Loop

You can’t tell how many digits a number has until you take it apart, which makes this a natural while-loop task.

Code (Java 21):

Output:

Number: 40517Digits: 5
Sum of digits: 17

remaining % 10 takes the last digit; remaining /= 10 removes it. The loop stops when nothing is left. The time is O(d), where d is the number of digits.

The same pattern reverses a number:

Code (Java 21):

Output:

 Reversed: 321

Note the edge case: the trailing zero of 1230 becomes a leading zero, so an int result shows 321.

Example 3: Loop Until a Value Is Reached (Collatz Steps)

Here the number of passes can’t be predicted at all. You only learn it by running the loop.

Code (Java 21):

Output:

6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1Steps: 8

Sentinel-Controlled While Loop in Java

A sentinel is a special value that means “stop”, such as -1 for “no more marks”. A sentinel loop needs two reads:

  1. a priming read before the loop, so the first condition check has real data, and
  2. an update read as the last statement of the body, so the next check gets a new value.
Whiteboard
Loading diagram...

The sentinel itself is never processed, because the check happens before the body runs.

Example 4: Average of Marks Until -1

Code (Java 21):

Sample run (the user typed 78, 92, 65, -1):

Enter a mark (-1 to stop): 78Enter a mark (-1 to stop): 92
Enter a mark (-1 to stop): 65
Enter a mark (-1 to stop): -1

Marks entered: 3
Average: 78.33333333333333

Sample run (the user typed -1 straight away):

Enter a mark (-1 to stop): -1
No marks entered

The count > 0 check avoids dividing by zero when the user enters no marks. Without the update read, mark would never change and the loop would add the same mark forever.

Example 5: Repeat Until the Input Is Valid (While Loop With Scanner)

Start the variable with a value the condition rejects, so the loop runs at least once. Use hasNextInt() so text like “abc” doesn’t crash the program.

Code (Java 21):

Sample run (the user typed abc, -5, 25):

Enter your age (1-120): abc'abc' is not a number.
Enter your age (1-120): -5
Out of range, try again.
Enter your age (1-120): 25
Age saved: 25

in.next() throws away the bad token. Without it, hasNextInt() would keep seeing “abc” and the loop would never end.

About closing the Scanner: calling close() on a Scanner that wraps System.in also closes standard input for the rest of the program. In small programs, create one Scanner and leave it open, or close it only at the very end.

Infinite While Loop in Java

An infinite loop is one whose condition never becomes false. The deliberate form is while (true), which is correct only when the body has a reachable exit: break, return, or an exception. Servers, game loops, and menus use this pattern.

Example 6: Menu Loop With while (true) and break

Code (Java 21):

Sample run (the user typed 1, 2, 7, 3):

1. Add 100  2. Show balance  3. Exit1
Added.
1. Add 100 2. Show balance 3. Exit
2
Balance: 600
1. Add 100 2. Show balance 3. Exit
7
Invalid choice
1. Add 100 2. Show balance 3. Exit
3
Goodbye!
break jumps out of the nearest enclosing loop immediately. You’ll study break and continue fully in Break and Continue in Java.

How to stop an accidental infinite loop: press Ctrl + C in the terminal, or click the Stop button in your IDE. Then find which variable in the condition never changes.

For Loop vs While Loop vs Do-While Loop in Java

Every for loop can be written as a while loop, and the output is the same:

Code (Java 21):

Output:

1 2 3 (for)1 2 3 (while)

The difference between while and do-while shows up when the condition is false from the start:

Code (Java 21):

Output:

do-while: selling a tickettickets = -1

Both loops used the same condition with zero tickets. The while loop correctly did nothing; the do-while sold a ticket that didn’t exist. So do-while is only right when one run is always correct, such as showing a menu once.

Featureforwhiledo-while
Condition checkedBefore each passBefore each passAfter each pass
Minimum runs001
Best forKnown count or rangeUnknown count; stop when data or state changesBody must run at least once
Counter declaredIn the header (scoped to the loop)Before the loopBefore the loop
Typical useGoing through an arraySentinel input, digit processing, retriesMenus, “ask once, then repeat”

Next lesson: Do-While Loop in Java.

Common Mistakes With While Loops in Java

Mistake 1: Forgetting to Update the Condition Variable

Wrong:

Output (Java 21, stopped after 2 seconds):

Booking seat, seats left: 2Booking seat, seats left: 2
Booking seat, seats left: 2
... (more than 2 million identical lines in 2 seconds)

Fix: add seats--; inside the body. Before running any while loop, ask three questions:

  1. Which variable does the condition read?
  2. Does the body change it?
  3. Does that change move it toward making the condition false?

Mistake 2: A Semicolon After the Condition

Wrong:

Result (Java 21): the program prints nothing and hangs.

Why: the ; is the whole loop body. n never changes, so the loop spins forever and the block below is never reached. Fix: remove the semicolon.

Mistake 3: Starting on the Wrong Side of the Condition

If a loop must run at least once, its starting value has to make the condition true. int age = 30; while (age < 1 || age > 120) skips the validation entirely. Start with a value the condition rejects (-1), as in Example 5, or use a do-while. Rule: the starting state and the exit state must be on opposite sides of the condition.

Mistake 4: = Instead of == in the Condition

Wrong:

Output (Java 21):

 Loop body ran 0 times

Why: found = false assigns false and the expression’s value is false, so the body never runs. Writing while (found = true) would do the opposite: loop forever. Both compile because the variable is a boolean. Fix: write while (!found).

Mistake 5: Using an int as the Condition

Wrong:

Compiler output (Java 21):

 IntCondition.java:4: error: incompatible types: int cannot be converted to boolean        while (n) {
^
1 error

Fix: while (n > 0).

Mistake 6: Code After while (true) With No break

Wrong:

Compiler output (Java 21):

 Unreachable.java:7: error: unreachable statement        System.out.println("Done");
^
1 error

Java knows the loop can never end, so it rejects the statement after it. Add a reachable break.

Mistake 7: continue Skips the Update

Wrong:

Output (Java 21): prints i = 0 and i = 1, then hangs forever.

Why: when i is 2, continue jumps back to the condition before i++ runs. Fix: update first.

Code (Java 21):

Output:

i = 1i = 2
i = 4
i = 5

Best Practices

  1. Write the condition so it reads like English: while (!unlocked && attempts < MAX_ATTEMPTS).
  2. Know your exit before you write the body: which change makes the condition false?
  3. Initialize deliberately; put the starting value on the correct side of the condition.
  4. In sentinel loops, always pair the priming read with an update read.
  5. Validate input with hasNextInt() instead of letting nextInt() crash.
  6. Give retries a limit (a maximum number of attempts) so a failure can’t hang the program.
  7. Use while (true) only with a clear, reachable break or return.
  8. Don’t busy-wait (loop doing nothing while you wait for time to pass or a flag to change); it burns CPU. Later lessons on multithreading cover proper waiting.
  9. Prefer a for loop when you’re simply counting from A to B.

Real-World Example: ATM PIN With Limited Attempts

This program combines a compound condition, a counter, and a flag, which is a very common while-loop shape in real applications.

Code (Java 21):

Sample run 1 (the user typed 1111, then 4321):

Enter PIN: 1111Wrong PIN. Attempts left: 2
Enter PIN: 4321
Card unlocked

Sample run 2 (the user typed 1, 2, 3):

Enter PIN: 1
Wrong PIN. Attempts left: 2
Enter PIN: 2
Wrong PIN. Attempts left: 1
Enter PIN: 3
Wrong PIN. Attempts left: 0
Card blocked

The loop has two exits built into one condition: success (unlocked) or running out of attempts. The PIN is hard-coded only to keep the demo short; real systems never store secrets in source code.

While Loop in DSA: GCD Using Euclid’s Algorithm

Many interview algorithms are while loops that run “until a value reaches zero”.

Code (Java 21):

Output:

a = 84, b = 36, a % b = 12a = 36, b = 12, a % b = 0
GCD = 12

Other everyday uses: reading a file line by line until no lines remain, processing tasks until a queue is empty, game loops, and retrying a network call a limited number of times.

Practice Problems

  1. Easy: Count how many digits a number has (for 0, the answer should be 1; handle it). Hint: the loop runs zero times for 0.
  2. Easy: Print the multiplication table of 7 using a while loop. Hint: counter from 1 to 10.
  3. Easy–Medium: Check whether a number is a palindrome (121 → yes, 123 → no). Hint: reverse it as in Example 2 and compare.
  4. Medium: Read positive numbers until the user enters 0, then print the largest. Hint: priming read plus update read.
  5. Medium: Find how many years ₹10,000 takes to grow past ₹20,000 at 8% yearly interest. Hint: while (amount <= 20000).

Try them in the ExamAdda online compiler.

Interview Questions on While Loop in Java

1. What is the difference between a while loop and a do-while loop?
while checks the condition before the body and can run zero times; do-while checks after the body and always runs at least once.

2. When would you choose while over for?
When the number of passes depends on runtime data: sentinel input, retries, digit processing, or draining a queue. Use for for a known count or range.

3. What is a sentinel value? What is a priming read?
A sentinel is a special input meaning “stop”. A priming read loads the first value before the loop so the first condition check has data.

4. Is while (true) bad practice?
Not by itself. It’s correct when the body has a reachable break, return, or exception, as in menus, servers, and event loops.

5. Why does while (n) compile in C but not in Java?
Java requires a boolean condition and does not treat integers as true or false.

6. What happens to a statement right after while (true) { } with no break?
Compilation fails with “unreachable statement”, because the compiler knows the loop can’t end.

7. How can continue cause an infinite while loop?
If continue runs before the update statement, the loop variable never changes and the same check repeats forever.

8. How many times is the condition checked in a loop whose body runs n times?
n + 1 times. The last check is the one that returns false.

Article Summary

  • A while loop repeats its body while a boolean condition is true and checks the condition before every pass, so it may run zero times.
  • You set up the state before the loop and update it inside the body; a missing update causes an infinite loop.
  • Sentinel loops need a priming read and an update read; validation loops start with an invalid value.
  • while (true) is valid only with a reachable break, return, or exception.
  • Use while for data-driven repetition, for for known counts, and do-while when the body must run once.

Conclusion

The while loop is Java’s tool for “keep going until something changes”. Before you run one, check three things: the starting state, the update that moves toward false, and the exit path. That habit prevents almost every while-loop bug. Next, see how Java runs a body at least once in the Do-While Loop in Java lesson, and sharpen your skills with ExamAdda practice questions.

Previous lesson: For Loop in Java
Next lesson: Do-While Loop in Java

References

Last updated: October 31, 2026. All examples tested on OpenJDK 21.

4. Series links

LinkURLStatus
Previous: For Loop in Javahttps://tech.examadda.org/java/for-loop-in-javaVerified (Previous button)
Next: Do-While Loophttps://tech.examadda.org/java/do-while-loopVerified (Next button)
Break & Continuehttps://tech.examadda.org/java/break-and-continueVerified (sidebar)
If-Else Statements (prerequisite)https://tech.examadda.org/java/if-else-statementsVerified (sidebar)
Compiler / Practice (call to action)/compiler, /practiceVerified (site navigation)
Scanner / user input lessonnot foundSuggestion: link from Example 5 once it exists
Multithreading (for busy waiting)Sidebar section only, no URLSuggestion

The same order issue as before applies: If-Else appears after the loop lessons in the sidebar.

5. Change log

Errors fixed

  • Placeholder text “Start writing your current affairs content here...” inside the article body: removed.
  • Unfair while vs do-while comparison. The old example used count > 0 for while but count < 0 for do-while, and never stated the starting value. The new example uses the same condition on both loops and shows the real output.
  • Restock example never said the starting stock; the output only implied it was 5. Replaced with fully specified examples.
  • Two different “last updated” dates; the Section 4 heading is missing its heading formatting; and the premium-video notice sits inside the intro. These are layout fixes to make in your editor.
  • Difficulty is shown as “Medium”; this is a beginner lesson.
  • Code not visible in the page text. The code doesn’t appear in the fetched text, so I couldn’t test your original code. Every example is now included in full, with tested output.

Taken from the reference (AlgoMaster). The reference has about 31 points: 26 were already covered in your lesson, 5 were expanded, 0 were new, and 0 were excluded. The expanded points are:

  • the input-validation loop, now with hasNextInt() and discarding bad tokens
  • exits from while (true) (break, return, or an exception)
  • retries, now with a fixed attempt limit
  • handling the zero-input case (the count > 0 check)
  • the infinite-loop checklist

Added from competitor research: the stray-semicolon trap, = vs ==, the int condition compile error, the “unreachable statement” compile error, continue skipping the update, how to stop a runaway loop with Ctrl+C, a dry-run table, the for → while rewrite, a sentinel flowchart, digit-sum and reverse-number programs (popular search queries), Euclid’s GCD, the PIN mini-program, 5 practice problems, and 8 interview questions.

Restructured: the opening now defines the loop in the first 60 words, a Key Takeaways box was added, long-tail search questions became headings, and the summary has 5 points.

Removed: nothing correct was removed. Only the examples that closely matched AlgoMaster were replaced.

Code testing: 21 programs were compiled and run on OpenJDK 21.0.12. The input programs were run with piped input; the console views show the typed values in place, and every program output line is real. The infinite-loop examples were run under a 2-second timeout, and their real behavior is described.

6. Image plan

  1. While-loop flowchart (the first Mermaid diagram as an SVG). Alt text: “Flowchart of a while loop in Java: check condition, run body, update state, repeat or exit”.
  2. Sentinel-loop flowchart (the second diagram). Alt text: “Sentinel-controlled loop with a priming read before the loop and an update read at the end of the body”.
  3. Side-by-side for / while / do-while (optional): the same 1-to-3 counter written three ways. Alt text: “The same counter written as for, while and do-while loops in Java”.