0
0
Javaprogramming~10 mins

While loop execution flow in Java - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop execution flow
Initialize variable
Check condition
Yes
Execute loop body
Update variable
Back to Check
Exit loop
Back to Check
The while loop starts by checking a condition. If true, it runs the loop body, updates variables, then checks again. It stops when the condition is false.
Execution Sample
Java
int i = 0;
while (i < 3) {
    System.out.println(i);
    i++;
}
Prints numbers 0, 1, 2 by looping while i is less than 3.
Execution Table
Stepi valueCondition (i < 3)ActionOutput
10truePrint 0; i = i + 10
21truePrint 1; i = i + 11
32truePrint 2; i = i + 12
43falseExit loop
💡 i reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at step 4, so the loop exits as shown in the execution_table row 4.
When is the variable i updated in the loop?
i is updated after printing in each loop iteration, as shown in the Action column of execution_table rows 1 to 3.
Does the loop body run if the condition is false at the start?
No, the condition is checked before the loop body runs. If false initially, the loop body never executes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at step 2?
A1
B0
C2
D3
💡 Hint
Check the 'i value' column in execution_table row 2.
At which step does the condition become false and the loop stops?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table to find when it is false.
If we change the initial i to 3, what happens to the loop execution?
ALoop runs once
BLoop does not run at all
CLoop runs three times
DLoop runs infinitely
💡 Hint
Recall that the condition is checked before the loop body runs, see key_moments about initial condition.
Concept Snapshot
while (condition) {
    // code runs while condition is true
    // update variables inside to avoid infinite loop
}

- Condition checked before each loop
- Loop stops when condition is false
- Variables usually updated inside loop
Full Transcript
This visual shows how a while loop works in Java. First, a variable i is set to 0. Then the loop checks if i is less than 3. If yes, it prints i and adds 1 to i. This repeats until i reaches 3, when the condition becomes false and the loop stops. The execution table tracks each step, showing i's value, the condition result, the action taken, and the output printed. The variable tracker shows how i changes after each loop. Key moments explain why the loop stops and when i updates. The quiz tests understanding of i's value at steps, when the loop ends, and what happens if i starts at 3.