While loop in Java

We use repeated actions to solve problems in day to day life. In programming also we use repeated actions to solve problems. For example, assume that you want to write a computer program that will add 1000 numbers given by a user. In order to solve this problem, we could have two options: to solve it sequentially or to do it using repetition in a loop . Both cases are shown below:

Using first option, perform task sequentially

Using second option, Perform Task using Loop

Here you can see the repetition in loop takes few lines compare to sequential solution to accomplish a same task. From the above example you can see the advantages of using repetition in loop. Java language provides different types of loop like for loop, while loop, do..while loop. Here we discuss the while loop and do..while loop.

while loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.


The expression (condition) in the while loop is evaluated, and if the expression (condition) is true , the code within the block is executed. This repeats until the expression(condition) becomes false . The expression(condition) should be updated during the repetitions, otherwise the program will never "break out" of while and lead to an infinite loop.



In the above program the loop will execute the code block 5 times. The first time the value of cnt is one, then its satisfy the condition cnt < =5. The the code block execute and update the value of cnt, that is cnt = cnt+1. This will repeated until the value of cnt=5 and then exit from the loop.

do...while loop

A do-while loop is similar to while loop statement but the do-while loop, the loop body will be executed first, then condition is evaluated. If the condition is true, the loop body will be executed. Otherwise the loop will be terminated. The advantage of a do...while loop is that it executes the block of code at least once , and then repeatedly executes the block depending on the condition.



In the above code, boolean enter=false;. Even the value of enter is false, the code block executed at least once. So the message displayed one time. If you give the condition to a while loop it will exit without showing the message, because the condition is false and never go inside the code block.

In the above case, the condition is false (enter=false) and the loop never execute.

The difference between do..while and while is that do..while loop evaluates its condition at the last of the loop instead of the first (in while loop the condition evaluate at first). Therefore, the statements within the do block are always executed at least once.
 (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About