The while and do

The while and do

The while and do

The while and do

The while and do

While and do-while

     

Lets try to find out what a while statement does. In a simpler language, the while statement continually executes a block of statements while a particular condition is true. To write a while statement use the following form:

while (expression) {
statement(s)
}

Lets see the flow of the execution of the while statement in steps:
1. Firstly, It evaluates the condition in parentheses, yielding true or false.
2. Secondly, It continues to execute the next statement if the condition is false and exit the while statement.
3. Lastly, If the condition is true it executes each of the statements between the brackets and then go back to step 1.

For example:

class Bonjour{
  public static void main (String args[]){
  int i = 0;  // Declare and initialize loop counter
  while (i < 5){ // Test and Loop
  System.out.println("Bonjour ")// Say Bonjour
  i = i + 1;  // Increment LoopCounter
  }
  }
}

In the above example, firstly the condition will be checked in the parentheses, while (i<args.length). If it comes out to be true then it will continue the execution till the last line and will go back to the loop again. However, if its false it will continue the next statement and will exit the while loop.

The output is as follows:

C:\vinod\xml>javac Bonjour.java

C:\vinod\xml>java Bonjour
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour


The while statement works as to for loop because the third step loops back to the top. Remember, the statement inside the loop will not execute if the condition is false. The statement inside the loop is called the body of the loop. The value of the variable should be changed in the loop so that the condition becomes false and the loop terminates.

Have a look at do-while statement now.

Here is the syntax:
do {
statement(s)
} while (expression);

Lets tweak an example of do-while loop.

class DoWhileDemo {
	public static void main (String args[]) {
		int i = 0; 
		do{
	           System.out.print("Bonjour");    
                   System.out.println(" ");
                   i = i + 1;                              
		   }while (i < 5); 
	}
}
 

In the above example, it will enter the loop without checking the condition first and checks the condition after the execution of the statements. That is it will execute the statement once and then it will evaluate the result according to the condition. 

The output is as follows:

C:\javac>java DoWhileDemo
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour

C:\javac>

You must have noticed the difference between the while and do-while loop. That is the do-while loop evaluates its expression at the bottom of the loop. Hence, the statement in the do-while loop will be executed once.