Java - do-while Statement

What is do-while Statement?

The do-while statement is loop statement.

The body with a do-while statement is executed at least once.

Syntax

The general form of a do-while statement is

do
    Statement
while (condition-expression);

The statement is executed first. Then the condition-expression is evaluated.

The do-while statement ends with a semicolon.

The condition-expression must be a boolean expression.

The statement can be a simple statement or a block statement.

If condition-expression evaluates to true, the statement is executed again.

do while loop continues until the condition-expression evaluates to false.

A break statement may be used to exit a do-while loop.

Example

The following code shows how to use do-while loop to compute the sum of integers between 1 and 10.

Demo

public class Main {
  public static void main(String[] args) {
    int i = 1;/* w w w .ja v a 2s .co  m*/
    int sum = 0;
    do {
      sum = sum + i; // Better to use sum += i
      i++;
    } while (i <= 10);

    // Print the result
    System.out.println("Sum = " + sum);

  }
}

Result