Java Do While || Java example

 

In the previous tutorial we have been thorough the concept of while loop and came to know its importance.So now in this tutorial we will get to know do while loop.

 

Java do while :

As we know now about while loop comparing it to do while i can say one thing in

-> In while loop we need a condition to be satisfied to execute at-least once.

while(condition){ // if condition satisfied
// block of code will get executed
}

 

-> In do while block of code will execute once before checking condition it’s the main difference between while and do while.

do{
// block of code gets executed once before while condition
}
while(condition);

 

Let’s do an example by considering a code to print numbers from 1 to 10 i am considering i = 10

public static int i = 10;

 

now add do block

do {

    System.out.println(i);

    i++;
}

 

then while condition now i considered i = 10 so while condition is not satisfied but code will execute once

while (i < 10);

 

do {

    System.out.println(i);

    i++;
}
while (i < 10);

java do while

 

now make i = 0

public static int i = 0;

and run the same piece of java do while code

do {

    System.out.println(i);

    i++; // increment i value to avoid infinite loop
}
while (i < 10);

 

java do while

 

 

 

Show Buttons
Hide Buttons
Read previous post:
Java While Loop || Java example

Java While Loop : In java programming, we have different requirements based on the type of work we are doing...

Close