Java Notes
A while loop repeats code only while a condition remains true. Use it when you do not know in advance how many times the work will repeat.
A while loop repeats code while a condition is true. Before every round, Java asks the condition. If the answer is true, Java runs the loop body. If it is false, Java skips the body and continues after the loop.
Use a while loop when you cannot say exactly how many rounds are needed before the program starts. For example, keep reading answers until someone chooses to stop, keep retrying while a connection fails, or keep playing while lives remain.
See the basic while loop step by step
This example counts from 1 to 5.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Java follows this order:
countstarts as 1.- Java checks
count <= 5. Since 1 is at most 5, the answer is true. - Java prints the current count, then
count++changes it to 2. - Java goes back to the
whilecondition and repeats the check. - When
countbecomes 6,6 <= 5is false. Java leaves the loop and prints the final message.
The update count++ is essential. It changes the value so the condition can eventually become false.
A while loop can run zero times
Unlike a do-while loop, while checks before it runs the body. When the condition is already false at the beginning, the body does not run at all.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
remainingLives > 0 is false immediately because the value is 0. Java skips Game continues and goes straight to Game over. This is useful when the work should happen only if a valid condition already exists.
When should you use while instead of for?
A for loop and a while loop can often do the same task. Choose the form that makes the reason for repeating easiest to understand.
| Situation | Better choice | Why |
|---|---|---|
| Print numbers 1 through 10 | for | You know the start, end, and update. |
| Keep asking until the user chooses Stop | while | You do not know how many answers the user will give. |
| Repeat while lives remain | while | The game state decides when it stops. |
| Visit each mark in an array | for-each or indexed for | The list provides the repetition count. |
Do not worry about a strict rule. If the condition that controls stopping is the main idea, while usually reads more naturally.
Use a sentinel value to stop input
A sentinel value is a special value that means “stop now.” For example, a program can keep adding positive numbers until the user enters 0. Here, 0 is not added to the total; it only tells the loop to finish.
This example needs a terminal because Scanner waits for keyboard input.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The first input is read before the loop so Java has a value to check. Inside the loop, Java adds only positive numbers, then asks for another number. When the user enters 0, number != 0 becomes false and the loop ends.
Reading again inside the loop is important. Without number = scanner.nextInt();, Java would keep checking the same old number forever.
Avoid an infinite loop
An infinite loop never stops because its condition never becomes false. This is usually a bug.
Before writing a while loop, answer three questions:
- What is the starting value or starting situation?
- What condition allows another round?
- What changes so the condition eventually becomes false?
If you cannot answer question 3, your loop may never end.
Try it yourself
Create a class named PasswordAttempts. Start with int attemptsLeft = 3. Use a while loop that prints the remaining attempts and decreases the number until it reaches 0. After the loop, print No attempts left.
Hint
Use while (attemptsLeft > 0). Put attemptsLeft--; inside the loop after printing the current number.
One working answer
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Run it, then start with 1 and 0. Check how a while loop behaves when the condition is already false.
Continue the lesson path