This post will discuss about while loop and do-while loop in Java.

Loops are used to continually execute a block of instructions until a particular condition is satisfied. There are four types of loops in Java: for-loop, enhanced for loop (for-each loop), while loop, and do-while loop. This post provides an overview of the while loop and do-while loop in Java.

1. While loop

A while loop in Java is a control flow statement that allows us to execute a set of statements repeatedly based on a specified boolean condition. The syntax of a while loop is:

 
The while loop evaluates the expression before each iteration of the loop, which should return a boolean value. If the expression is true, the code inside the while block is executed. The loop terminates when the expression evaluates to false and the control moves to the next statement after the loop. To illustrate the working of a while loop, consider the following code, which prints the numbers 0 to 9 on separate lines.

Download  Run Code

 
If the expression never evaluates to false, it will result in an infinite loop, as shown below:

2. Do-while loop

There is another variation of the while loop called the do-while loop. It is similar to the while loop, except that the condition is checked at the end of each iteration instead of the starting of the loop. This ensures that the code block is executed at least once, even if the condition is false. The syntax of a do-while loop is:

 
Here, the expression is evaluated after each iteration of the loop. If the expression is true, the code block inside the loop is executed again. If the expression is false, the loop terminates, and the control moves to the next statement after the loop. To illustrate the working of a do-while loop, consider the following example, which prints the numbers 0 through 9 like previous example.

Download  Run Code

That’s all about the while loop and do-while loop in Java.