while loop in java is used to perform iteration on the block of code. Iteration will continue until specified Boolean condition is true. Once the condition becomes false loop will stop and execution will terminate.
While loop can be used in iteration when number of iteration is not fixed. Otherwise we can go with for loop to iterate. Because for loop required the iteration times.
Syntax of While Loop
while (condition){
//code block
Increment or decrement
}
If we see the above syntax of while loop, there are condition, code block and Increment or decrement.
Here if condition check return true then code block will execute. And after that there will be Increment or decrement.
Otherwise if condition inside while() will fail then code block will not execute.
Program to demonstrate while loop
public class Main {
public static void main(String args[]) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
Output
0
1
2
3
4
In the above program you can see that value of i is initialized with 0. And our conditional check is i<5, means code inside while loop will execute only when value of i is smaller that 5. And each time when condition satisfy value of i is getting increased by 1.
Now when value of i is become 5, while condition got failed and execution is terminated.
So from the output of the above program you can see that value is printed upto 4 only.