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.


The general form of a do-while statement is

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.


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


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

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