Do While Loop In Java
do-while loop
There is another loop control structure which is very similar to the while statement called as do while statement. The only difference is that the expression which determines whether to carry on looping is evaluated at the end of each loop.
Syntax
do {
Statements;
} while (test condition);
Let’s understand with the flowchart, given below.
In do-while loop, the loop body is executed at least once, if condition is false. The loop repeats body , when the condition is true. However, in while loop, the statement doesn’t execute the body of the loop even once, if the condition is false. Due to this “do-while loop” is also called exit-control loop.
Let’s see an example of do-while loop, given below.
Code
- public class DoWhileExm {
- public static void main(String[] args) {
- int n = 1;
- do {
- System.out.println("do-while loop : " + n);
- n++;
- } while (n < 10);
- }
- }
Output
Summary
Thus, we learnt “do while loop” is very similar to the while statement. The only difference is that of the expression and also learnt how to create it in Java.