Java Tutorial Java Advanced Java References

Java do Keyword



The Java do keyword is used with while keyword to create a do-while loop. A while loop allows a set of statements to be executed repeatedly as long as a specified condition is true.

Whereas, the do-while loop is a variant of while loop which execute statements before checking the conditions. Therefore the do-while loop executes statements at least once.

Syntax

do {
  statements;
}
while (condition);

Flow Diagram:

Java Do-While Loop

Example

In the example below, even if the condition is not fulfilled, the do-while loop executes the statements once.

public class MyClass {
  public static void main(String[] args) {
    int i = 10;
    int sum = 0;
    do{
        sum = sum + i;
        i = i+1;
    }
    while (i <= 5);
    System.out.println(sum);  
  }
}

The output of the above code will be:

10

❮ Java Keywords