FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Do While Loop in Java







do-while loop is similar to while loop, however there is a difference between them: In while loop, condition is evaluated before the execution of loops body but in do-while loop condition is evaluated after the execution of loop's body.

Syntax of do while loop:

do
{
   statement(s);
} while(condition);

How do-while Loop works?

First, the statements inside loop execute and then the condition gets evaluated, if the condition returns true then the control gets transferred to the "do" else it jumps to the next statement after do-while.

Note: The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely.
do while-loop

do-while loop example

class DoWhileLoopExample {
    public static void main(String args[]){
         int i=10;
         do{
              System.out.println(i);
              i--;
         }while(i>1);
    }
}

Output

10
9
8
7
6
5
4
3
2

Example: Iterating array using do-while loop

Here we have an integer array and we are iterating the array and displaying each element using do-while loop.

class DoWhileLoopExample2 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0
         int i=0;
         do{
              System.out.println(arr[i]);
              i++;
         }while(i<4);
    }
}

Output

2
11
45
9

You may also Find this interesting

JAVA Static Keyword

JAVA Inheritance

JAVA Types of Inheritance

JAVA Aggregation

JAVA Association







Leave Comment