Java do while loop statement

Introduction

The do-while loop runs its body at least once since its conditional expression is at the end of each loop.

Its general form is

do {  
      // body of loop  
} while (condition);                                                                              

Each iteration of the loop executes the loop body first and then checks the condition.

If this expression is true, the loop will repeat.

Otherwise, the loop terminates.

The condition must be a Boolean expression.

// Demonstrate the do-while loop.
public class Main {
  public static void main(String args[]) {
    int n = 10;/*  www  .  j  a  va 2 s  .  c  o  m*/

    do {
      System.out.println("tick " + n);
      n--;
    } while(n > 0);
  }
}

The code above can be written more efficiently as follows:

do {  
  System.out.println("tick " + n);  
} while(--n > 0); 



PreviousNext

Related