Java While Loop
A while loop lets your program repeat a block of code again and again, for as long as a condition stays true. Instead of copying the same statements over and over, you write them once and let Java run them until there is nothing left to do.
What is a while loop?
Think of a while loop as a question that Java keeps asking before every pass: "Is this condition still true?" If the answer is yes, it runs the code inside the braces once more, then asks again. The moment the answer becomes no, the loop stops and your program continues with whatever comes after it.
Basic while loop syntax
int i = 0;
while (i < 5) {
System.out.println("i is now " + i);
i++;
}
// Output:
// i is now 0
// i is now 1
// i is now 2
// i is now 3
// i is now 4Notice the three parts working together: we start with i set to 0, the condition i < 5 decides whether to keep going, and i++ moves us one step closer to stopping. If you forget that last step, i would stay 0 forever and the loop would never end.
A practical example
While loops shine when you do not know in advance how many times you will repeat. Here we keep doubling a number until it passes a target, without knowing the exact count of steps beforehand.
Repeat until a goal is reached
int value = 1;
int steps = 0;
while (value < 100) {
value = value * 2;
steps++;
}
System.out.println("Reached " + value + " in " + steps + " doublings");
// Output: Reached 128 in 7 doublingsThe three things every while loop needs
- Initialization: set up a starting value before the loop begins.
- Condition: a boolean test checked before each pass; the loop runs only while it is true.
- Update: change something inside the loop so the condition will eventually become false.
Exercise: Java While Loop
When is a standard while loop's condition evaluated relative to its body?