LogIn
I don't have account.

do while loop in java

DevSniper
146 Views

do while loop is a fundamental control flow statement of Java. do while loop is used to run some block of code several times based on certain condition. do while loop ensures that the loop body is executed at least once regardless of whether the condition is initially true or false. It offers a structured and efficient way to handle repetitive tasks.

//initialization
do
{
    // loop body
   //updation
}while(condition);
  • condition : It evaluated after every execution of the loop body. Here we define condition of the execution of loop body. if the condition is false we stop execution of the loop body and terminate loop.
  • do-while loop guarantees at least one execution of the loop body regardless of whether the condition is initially true or false.
  • do while loop is used to execute a block of code (loop body) several times.
  • do while loop is a exit control loop it verifies condition after executing of the loop body.
  • do while loop simplifies repetitive tasks.
  • It is useful when you want to execute a block of code at least once and then repeatedly execute it based on certain condition.
  • Simple do while loop
  • Nested do while loop
  • Infinite do while loop

Simple do while loop

public class RebootMemory 
{
    public static void main(String[] args) 
    {
        int i=3;
        do {
            System.out.print(i+" ");
            i++;
        } while(i<10);
    }
}
3 4 5 6 7 8 9

Nested do while loop

if we place do while loop inside another loop this is called nested do while loop. inner do while loop execute completely for every outer loop execution. outer loop will be any loop like for loop, while loop or do while loop.

public class RebootMemory 
{
    public static void main(String[] args) 
    {
        for( int i=1 ; i<=2; i++ ) {
            System.out.println("Inside Outer loop i : "+i);
            int j=1;
            do{
                System.out.println("=>  inside inner loop i :- "+i+" and j : "+j);
                j++;
            }while(j<=3);
        }
    }
}
Inside Outer loop i : 1
=>  inside inner loop i :- 1 and j : 1
=>  inside inner loop i :- 1 and j : 2
=>  inside inner loop i :- 1 and j : 3
Inside Outer loop i : 2
=>  inside inner loop i :- 2 and j : 1
=>  inside inner loop i :- 2 and j : 2
=>  inside inner loop i :- 2 and j : 3

Infinite do while loop

if we define a condition that never becomes false, loop become Infinite Loop.

do {
   // loop body
}while(true);
do{
   // loop body
}while(2<5);
int i=3;
do{
   System.out.println(i);
}while(i<5);