Java: Do-While Loop

do-while loop

Do While Loop In Java

Looping is a cardinal feature of any programming language. We will be learning about Do While Loop In Java programming language.

Using loops saves the programmer from the hassle of writing the same code again and again to obtain the desired results. We have three different loops in programming:

  • For Loop.
  • While Loop.
  • Do- While loop.

Understanding the Concept

A do-while loop is a functionality that is similar to the standard while loop except the fact that in this type of looping technique the body of the loop will be executed at least once, even if the condition check returns false.. Also, a do-while loop evaluates the condition at the end of the loop.

It is also known as Post-tested loop. The steps in this looping technique are:

  • The control flow first enters the loop.
  • The body of the loop is executed initially.
  • Now, the condition specified is evaluated.
    • If it returns true, the body of the loop is executed again.
    • If it returns false, the control flow falls out of the loop
Do while loop

Syntax

do
{
    // loop body
    
    update_count
}
while (condition_check);

Now that we have seen the syntax of the do-while loop, let us understand how it works via an example. 

Suppose we want to print a table of 4 up till 10. Instead of writing the code again and again we can use the do while loop as follows:

Run
public class Main 
{ 
    public static void main(String args[]) 
    { 
        int i = 1; 
        do {

             System.out.println(i*4);

               i++;
           }

         while (i < 11);
    }
}

Output

4
8
12
16
20
24
28
32
36
40