While Loop in Java

while loop is very similar to for loop. Only the difference is, while loop has only one property inside parenthesis instead of 3 properties likewise for loop. We set and initial value separately and do post operation inside loop block.
Syntax:

while (condition) {
statements here
}
As we can see above, we have one property inside parenthesis starting with while keyword.

It continues to execute the program until the condition fails. DO not forget to do post operation manually otherwise it will be infinite loop.


Examples:

If we want to print only even numbers upto 10, we can do this:
Code:

public class LearnWhileLoop { public static void main(String[] agrs) { int i = 0; while(i <= 10) { System.out.println(i); i += 2; // i = i + 2 } } }
we can see in above program, we set i to 0 somewhere else. Inside while loop, we checked condition if i is less than or equal to 10. And if it is, execute the code below. Because we only want print even numbers, we incremented i by 2.
Output:
0
2
4
6
8
10


What if we want all numbers divisible by 5 up to 50? Lets see this example:
Code:

public class LearnWhileLoop { public static void main(String[] agrs) { int i = 1; while(i <= 50) { if(i%5 == 0){ System.out.println(i); } i++; } } }
Output:
5
10
15
20
25
30
35
40
45
50


For Loop in Java Previous Next Do While Loop in Java