The while loop is an entry-controlled loop that repeatedly executes a block of target statements as long as its boolean condition remains true. The condition is verified at the entry gate before each iteration.
// While Loop Syntax:
while (boolean_condition) {
// Loop body statements
// Update statement (increments, decrements, or state change)
}
A classic university exam program demonstrating a while loop where the iteration count depends on the numerical value:
public class ReverseNumberDemo {
public static void main(String[] args) {
int number = 12345;
int reversed = 0;
System.out.println("Original Number: " + number);
while (number != 0) {
int lastDigit = number % 10; // Extract last digit
reversed = reversed * 10 + lastDigit; // Append to reversed
number = number / 10; // Discard last digit
}
System.out.println("Reversed Number: " + reversed); // 54321
}
}
| Iteration | Condition (number != 0) | lastDigit (% 10) | reversed (rev * 10 + d) | number (/ 10) |
|---|---|---|---|---|
| Initial | — | — | 0 | 12345 |
| Cycle 1 | 12345 != 0 (True) | 5 | 5 | 1234 |
| Cycle 2 | 1234 != 0 (True) | 4 | 54 | 123 |
| Cycle 3 | 123 != 0 (True) | 3 | 543 | 12 |
| Cycle 4 | 12 != 0 (True) | 2 | 5432 | 1 |
| Cycle 5 | 1 != 0 (True) | 1 | 54321 | 0 |
| Cycle 6 | 0 != 0 (False!) | Loop Terminates Immediately | ||
Exam Question: "What is the minimum number of times a while loop executes?"
Answer: Zero times! Because the while loop evaluates its condition at the entry point before entering the body, if the initial condition is false (e.g. int i = 10; while(i < 5)), the body will not execute even a single time.
Now let us explore the Do-While loop, which guarantees execution at least once. Proceed to: Java Do-While Loop →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Exit-controlled counterpart.
Counter-controlled iteration.
Controlling loop cycles.
Loop tracing drills.