Java do while loop

In this chapter you will learn:

  1. Why do we need Java do while loop
  2. Syntax for Java do while loop
  3. Example - How to use do-while statement
  4. How to create a simple help menu with while loop and switch statement

Description

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

Syntax

Its general form is:


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

Example

Here is an example to show how to use a do-while loop.

 
public class Main {
  public static void main(String args[]) {
    int n = 10;//  w ww  . j av  a 2s.co  m
    do {
      System.out.println("n:" + n);
      n--;
    } while (n > 0);
  }
}

The output:

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

 
public class Main {
  public static void main(String args[]) {
    int n = 10;/*w w w  .j a  v  a2 s  .com*/
    do {
      System.out.println("n:" + n);
    } while (--n > 0);
  }
}

The output is identical the result above:

Example 2

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;/*from w  ww  .j  a  va 2s.  co m*/
    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:

Next chapter...

What you will learn in the next chapter:

  1. When to use break statement
  2. Syntax for break statement
  3. Example - How to exit a for loop for a condition
  4. Example - break ut of a while loop
  5. How to use break statement to exit an infinite loop
  6. How to break just one layer of the nested loop
  7. How to break from a switch statement
  8. How to break where you want
Home »
  Java Tutorial »
    Java Langauge »
      Java Statement
Java if Statement
Java if else Statement
Java if else ladder statement
Java nested if statement
Java switch Statement
Java for loop
Java for each loop
Java while Loop
Java do while loop
Java break statement
Java continue statement
Java Comments
Java documentation comment(Javadoc)