The while Statement : While Loop « Statement Control « Java Tutorial






  1. One way to create a loop is by using the while statement.
  2. Another way is to use the for statement

The while statement has the following syntax.

while (booleanExpression) {
    statement (s)
}
  1. statement(s) will be executed as long as booleanExpression evaluates to true.
  2. If there is only a single statement inside the braces, you may omit the braces.
  3. For clarity, you should always use braces even when there is only one statement.

As an example of the while statement, the following code prints integer numbers that are less than three.

public class MainClass {

  public static void main(String[] args) {
    int i = 0;
    while (i < 3) {
      System.out.println(i);
      i++;
    }
  }

}

To produce three beeps with an interval of 500 milliseconds, use this code:

public class MainClass {

  public static void main(String[] args) {
    int j = 0;
    while (j < 3) {
      java.awt.Toolkit.getDefaultToolkit().beep();
      try {
        Thread.currentThread().sleep(500);
      } catch (Exception e) {
      }
      j++;
    }
  }

}

Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but relies on the break statement to escape from the loop.

public class MainClass {

  public static void main(String[] args) {
    int k = 0;
    while (true) {
      System.out.println(k);
      k++;
      if (k > 2) {
        break;
      }
    }
  }

}








4.4.While Loop
4.4.1.The while Statement
4.4.2.Using the while loop to calculate sum
4.4.3.While loop with double value
4.4.4.Java's 'labeled while' loop