do-while statement

To execute the body of a while loop at least once, you can use the do-while loop. Its general form is


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

Here is an example to show how to use a do-while loop. It generates the same output as before.

  
public class Main {
  public static void main(String args[]) {
    int n = 10;
    do {
      System.out.println("n:" + n);
      n--;
    } while (n > 0);
  }
}  

The loop in the preceding program can be written as follows:


n:10
n:9
n:8
n:7
n:6
n:5
n:4
n:3
n:2
n:1
  
public class Main {
  public static void main(String args[]) {
    int n = 10;
    do {
      System.out.println("n:" + n);
    } while (--n > 0);
  }
}  

The output:


n:10
n:9
n:8
n:7
n:6
n:5
n:4
n:3
n:2
n:1

The following program implements a very simple help system with do-while loop and switch statement.

  
public class Main {
  public static void main(String args[]) throws java.io.IOException {
    char choice;
    do {
      System.out.println("Help on:");
      System.out.println(" 1. A");
      System.out.println(" 2. B");
      System.out.println(" 3. C");
      System.out.println(" 4. D");
      System.out.println(" 5. E");
      System.out.println("Choose one:");
      choice = (char) System.in.read();
    } while (choice < '1' || choice > '5');
    System.out.println("\n");
    switch (choice) {
      case '1':
        System.out.println("A");
        break;
      case '2':
        System.out.println("B");
        break;
      case '3':
        System.out.println("C");
        break;
      case '4':
        System.out.println("D");
        break;
      case '5':
        System.out.println("E");
        break;
    }
  }
}  

Here is a sample run produced by this program:


Help on:
 1. A
 2. B
 3. C
 4. D
 5. E
Choose one:
Home 
  Java Book 
    Language Basics  

Statement:
  1. Simplest if statement
  2. If else statement
  3. switch statement
  4. while loop
  5. do-while statement
  6. for Loop
  7. for each loop
  8. break to Exit a Loop
  9. continue
  10. return statement returns from a method.
  11. Comments