Java do while loop Tutorial

“Don’t repeat the same mistake and expect a different result”

In this section we’re assuming you already familiar with the while loop.

The do while loop is another variant of the while loop and its difference is that it will run the body of the loop first and then check the condition of that loop. In such case, even if the output of the condition set for the loop is false, we’re guaranteed that at least the body will run for once.

Java do while syntax

Here’s the structure of the do while loop:

do {
  // code block to be executed
}
while (condition); `do` keyword: we use the keyword `do` and the pair of braces `{}` that come afterwards to define the body of the loop.

Again this body is guaranteed to run at least once before checking the condition of the loop.

`while` keyword: we use the `while` keyword and the parentheses that comes afterwards to set the condition of the loop.

Notes:

  • As long as the condition is true, the body of the loop will
    run.

  • Also the `while()` statement is set after the closing brace `}`
    of the `do` keyword.

  • We use the semicolon `;` after the `while()` statement.

Java do while Example:

public class Simple {
public static void main(String[] args) {
int i = 0;
do{
System.out.print(i+", ");
i++;
}while (i != 100);
}
} Output:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,

In this example, first the body of the loop ran and so the value of the i variable is sent to the output stream and also it is incremented by one before the condition of the while loop is checked. After that the condition is checked to see if the value of this variable is equal to 100 or not and because this value is far away from 100, then the result of the condition is true and the body will run again.

This process will repeat itself until the value of the i variable becomes 100 which in that case the loop will break and the instructions after the loop will be executed.