Do While Loop in Java

Do while loop is an another variant of while loop. Only difference is, in do while loop the code executes once before checking condition.

Either the given condition is true or flase, the code inside do while loop block executes once and then only it checks the condition. If the condition is true, it goes for next iteration else stops the loop.
Syntax:

do {
statements
} while(condition);
Everything else and afterwards, works same as while loop.


Example:

Lets say I want to print even numbers upto 10. But I want to include 0, either it counts as even or not. Lets see this example:
Code:

public class LearnDoWhileLoop { public static void main(String[] args) { int i = 0; do { System.out.println(i); i += 2; } while(i <= 10); } }
we can see in above program, we printed 0 first and then increased i by 2. Then checked condition if it is less than or equal to 10 or not. So it will will print numbers adding 2 everytime till value of i reaches 10.
Output:
0
2
4
6
8
10


While Loop in Java Previous Next Break and Continue in Java