News:

GinGly.com - Used by 85,000 Members - SMS Backed up 7,35,000 - Contacts Stored  28,850 !!

Main Menu

The do-while statement

Started by VelMurugan, Nov 21, 2008, 10:23 PM

Previous topic - Next topic

VelMurugan

The do-while statement

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");     // Say Bonjour
            System.out.println(" ");
            i = i + 1;               // Increment LoopCounter
    }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>javac DoWhileDemo.java

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


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.