While & Do While Loops


This image has an empty alt attribute; its file name is image-9.png

Hi there! In our previous post, we learnt about Java for loop. In this post, we will go over Java while and do…while loops.

Java while loop statement that is used to run a block of code if the number of iteration is not fixed and a certain condition is met.  

Let’s understand the required syntax for code first;

while (statement){    

//Block of code 

}  

statement: If the condition is true then a block of code is executed and the condition is evaluated again until the condition is false, then the loop stops.

Example 1: Print values between 1 to 6

Example 2: Adding numbers together until the condition is false

The do while loop is similar to while loop. Difference is the block of code will be executed one time before the condition is checked. So that means first we will have a block of code then do.. while at the end of the coding body.

The required syntax for code is like following;

do{    

//Block of code 

}while (statement); 

statement: Condition is tested already. If the condition is true  then a block of code is executed and the condition is evaluated again,  If the condition is true  then the condition is evaluated again, until the condition is false  then the loop stops.

Let’s review the same examples with do… while loop.

Example 1: Print values between 1 to 6

Example 2: Adding numbers together until the condition is false

I hope you have a basic understanding of three different looping statements now.

Leave a comment