java while loop – How to use while and do while loop in java

While loop in Java

Loops are the way to execute specified block of code again and again to a given number of times. There will be scenarios in programming life when you need one or the other type of loop in order to achieve certain task.

Types of loops are supported in Java

  1. for loop
  2. while loop
  3. do… While loop

This chapter will explain about While and do..While loops in Java. Links for other loops can be found at bottom of page.

A while loop in Java keeps on executing block of statement(s) as long as given condition, a Boolean, is true.  As condition becomes false the pointer/execution will move to next statement, outside of while block.

Structure of while loop in Java

This type of loop (while loop) will iterate over given sequence, as follow:

While (condition){

                //Code to be executed;

}    

Example of using While loop in Java

The example below loops over variable a till its value is less than or equal to 10, started from 1.



See graphic of above example

The output of the above code will be:

Current value of a = 1

Current value of a = 2

Current value of a = 3

Current value of a = 4

Current value of a = 5

Current value of a = 6

Current value of a = 7

Current value of a = 8

Current value of a = 9

Current value of a = 10

do while loop in Java

The do…while is just like while loop except the code inside do..while loop is executed at least once. There may be scenario where you want to run code at least once, then check for some condition and keep on executing unless condition is false.

 

Structure of do while loop in Java

do

{

                //Code to be executed;

}

while(condition);

As you can see in above structure of do…while, first code is executed and then Boolean condition is evaluated. If condition turns true then it will iterate or otherwise will exit loop and flow move to next line of execution outside loop.

Example of using do..while loop in java

This example uses do…while loop:



See graphic of above example

The output of the above code will be:

Current value of a = 1

Current value of a = 2

Current value of a = 3

Current value of a = 4

Current value of a = 5

Current value of a = 6

Current value of a = 7

Current value of a = 8

Current value of a = 9

Current value of a = 10

Also see java for loop

Was this article helpful?

Related Articles

Leave A Comment?