Java: Do While Loop

There is a loop in the java programming language called the do-while loop. Normally a loop checks for the condition and if the condition satisfies the need then the loop block gets executed. Here it is completely the opposite.

In the do-while loop, the first thing is that it will execute the loop and then checks for the condition whether it is satisfied or not, it is a sort of exit control loop.

Syntax

do
{
    //loop
}
while(condition)

Example

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        int age = 10;

        do
        {
            System.out.println("Not Allowed! You Are Too Young For The Roller Coaster!");
            age++;
        }
        while (age < 15);
    }
}

Output:

Not Allowed! You Are Too Young For The Roller Coaster!
Not Allowed! You Are Too Young For The Roller Coaster!
Not Allowed! You Are Too Young For The Roller Coaster!
Not Allowed! You Are Too Young For The Roller Coaster!
Not Allowed! You Are Too Young For The Roller Coaster!

So this is a simple do while loop where we are telling if the age is less than 15 do the following, loop until it reaches 14 and when it checks for the 15 iterations, and it increments the loop ends there.

Thu, 10/28/2021 - 12:21

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags