While loop in java is used to execute a block of code multiple times, until a condition becomes true. Unlike for loop, there is no initialization and increment/decrement step in while loop.
While loop is preferred when the number of iteration is not fixed.
while(condition_expression) { // while loop code block statements; }
condition_expression is a boolean expression which gets evaluated every time before control enters while loop's code block. Here is the description of while loop control flow.
- First of all, while loop evaluates condition_expression inside the parenthesis.
- If condition_expression evaluates to true, then while loop code block gets executed.
- condition_expression is evaluated again.
- This execution process continues until the condition_expression evaluates false.
- Whenever condition_expression evaluates to false, while loop terminates and control goes to the next statement after the while loop.
Here is the flowchart of while loop execution

Java While Loop Example Program
public class WhileLoop { public static void main(String[] args) { int count = 0; while (count < 5) { System.out.println(count); count++; } } }Output
0 1 2 3 4
In above program, while loop executes print statement 5 times, till the time the value of count variable is less than 5. With every iteration the value of count variable is incremented. As soon as value of count becomes 5 while loop terminates.
Here are the execution steps for each iteration of while loop in above program.
Iteration Count | Variable | Condition (count < 5) |
While Loop Code Block |
---|---|---|---|
1 | count = 0 | true | Print count(0). count is incremented to 1 |
2 | count = 1 | true | Print count(1). count is incremented to 2 |
3 | count = 2 | true | Print count(2). count is incremented to 3 |
4 | count = 3 | true | Print count(3). count is incremented to 4 |
5 | count = 4 | true | Print count(4). count is incremented to 5 |
6 | count = 5 | false | Not Executed |
- The condition in while loop is a boolean expression.
- Unlike for loop, there is no initialization and update statements.
- Opening and Closing braces are not required for single statement inside while loop code block.
For Example:
while(i < 100)
sum+= i; - We can also use infinite while loops like while(1), which will never terminate. You should add terminating condition using break statement in order to terminate infinite while loop.
For Example:
while(1) {
if(.....){
break;
}
}