The while Loop: Basic Syntax and Execution Flow
What You'll Learn
You'll discover how Java's while loop repeatedly executes code as long as a condition remains true, checking the condition before every iteration.
What Is a while Loop?
A while loop lets you repeat a block of code without writing it multiple times. Think of it like a sign at a restaurant door: "While there are customers waiting, keep seating people." The host checks the condition (are people waiting?) before each round of seating. If nobody's waiting, they stop.
Basic Syntax
while (condition) {
// code to repeat
}
The condition is a boolean expression (just like in if statements). If it evaluates to true, the code block runs. After executing the block, Java jumps back and checks the condition again. This continues until the condition becomes false.
Execution Flow
- Evaluate the condition
- If
false, skip the entire loop body and continue after it - If
true, execute the loop body - Return to step 1 (check condition again)
Simple Example
int count = 1;
while (count <= 3) {
System.out.println("Count is: " + count);
count++;
}
System.out.println("Loop finished");
Output:
Count is: 1
Count is: 2
Count is: 3
Loop finished
Here, the condition count <= 3 is checked before each iteration. When count becomes 4, the condition evaluates to false, and the loop terminates.
⚠️ Important: If the condition is false initially, the loop body never executes—not even once!
Key Takeaway: A while loop repeats code as long as its condition is true, checking the condition before each iteration, making it perfect for situations where you don't know in advance how many times you need to loop.