do-while Loop

Loop constructs are used to iterate a piece of code again and again until specified condition is true. for example if want to print "hello world" message 10 times, without loop constructs we have to write printing statemnt 10 times. In order to simplifying the iteration process, loop constructs are introduced. Loop in java are same as in c or c++. In java we have while, do-while, for and for each.


Syntax of do-while loop :

    do
{
Statement1;
Statement2;
...........
...........
Statements;
}while(condition);

Difference between do-while and while is time of condition checking. In do-while first statements are executed then condition is checked. If condition is true then again statements are executed. In do-while if condition is false in that case also at least one time all statements are executed.



In while loop condition has to be specified, otherwise compiler will generate an error.


Example :


//file:even1.java
// www.jgyan.com
class even1
{
public static void main(String ...arg)
{
int i=2;
do
{
System.out.println(i);
i=i+2;
}while(i<=100);
}
}


To see the difference between while and do-while execution, specify a condition which is false. In case of do-while loop body will execute one time, but in case of while loop that will not happen.


Example :


// file : diff.java
// www.jgyan.com
class diff
{
public static void main(String ...arg)
{
int i=10;
while(i<10)//condition is false
{
System.out.println("While loop:"+i);
i++;
}
do
{
System.out.println("do-while loop:"+i);
i++;
}while(i<10);//condition is false
}
}
/* Output:
do-while loop:10
*/


From above program we can see condition is false, but still do-while loop executed once.