Java Do-while

The Java do-while loop executes a block of statements in do block, and evaluates a boolean condition in while block to check whether to repeat the execution of block statements again or not, repeatedly.

The important point to note is that the statements in the do block are executed at least once, even if the condition in the while statement is always false.

1. Syntax

The general syntax of a do-while loop is as follows:

do {

    statement(s);
} while (condition-expression);

Let us note down a few important observations:

  • The do-while statements end with a semicolon.
  • The condition-expression must be a boolean expression.
  • The statement(s) can be a simple statement or a block of statements.
  • The statement(s) are executed first, then the condition-expression is evaluated later.
  • If the condition evaluates to true, the statement(s) are executed again.
  • This loop continues until the condition-expression evaluates to false.
  • Like in a for loop and a while loop, a break statement may be used to exit a do-while loop.

2. Java Do-while Example

The following program demonstrates the basic usage of a do-while loop. The program prints the numbers from 1 to 5.

int i = 1;
do {
    System.out.println(i);
    i++;
}
while (i <= 5);

The program outputs:

1
2
3
4
5

3. Difference between while Loop and do-while Loop

The main difference between do-while loop and while-loop is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.

int i = -10;

//Simple while loop

while (i > 0) {
  System.out.println(i);  //Does not print anything
  i++;
}

//Do-while loop

do {
  System.out.println(i);    //Prints -10 and then exits
  i++;
} while (i > 0);

Other than this there is no difference between both loops.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode