PREV NEXT
Java While loop executes a set of statements repeatedly until a given condition remains true.
Syntax for Java While loop:
while(condition)
{ //statements } |
Example:
1 2 3 4 5 6 7 8 9 10 11 |
int i = 5; while ( i != 0 ) { System.out.println(“value:”+i); --i; } |
Output:
value:5
value:4 value:3 value:2 Value:1 |
In the above program, the value of i is printed until it is not equal to zero. When the value of i reaches 0, the execution of the loop is terminated.
Infinite loop:
When we explicitly mention the condition value as true in the while loop, then it repeats endlessly. If we would like to break the infinite loop in between, we can use break; statement.
while(true) { //statements } |