7) Conditionals & Loops Lesson

What is a Do-While Loop?

3 min to complete · By Ryan Desmond

The do-while loop is similar to the while loop, except the syntax is slightly different.

How does the Do-While Loop Work in Java?

In the do-while loop, the condition is evaluated at the bottom instead of the top, like in the while loop. This means the code inside the do-while will always be executed at least once. Its syntax is as follows.

do {  
  // code to execute  
} while (boolean condition);

Infinite Do-While Loop

As with the while loop, if the condition in your do-while loop is always true then your loop will run forever: this almost always must be avoided!

Do-While Loop in Java Example

A program that prints out a statement 10 times would be as follows.

class Main{  
  public static void main(String[] args){  
    int x = 1;  
    do{  
      System.out.println("x is: " + x);  
      x++;  
    } while(x < 11);  
  }  
} 

After 10 is printed, x is incremented to 11. The condition is checked and evaluated as false so it does not repeat when x is 11.

And that's it! As with the while loop, there's not too much to stay about these loops.

Summary: What is the While Loop in Java?

  • The do-while loop will continually execute its code until its condition is false
  • Infinite do-while loops should almost always be avoided
  • A do-while loop has its condition at the end
  • A do-while loop will always execute its code at least once

Syntax

Here's the syntax for the do-while loop, where you can substitute the variables starting with your_ with your values.

do{  
  // your_code
} while (your_condition);