while Loop in Java With Examples

while loop in Java repeatedly executes a block of statement while the given condition is true.

Syntax of the while loop is as follows-

Block of code that is executed with in a loop is enclosed with in curly braces. If only a single statement is executed with in while loop then curly braces are optional.

Java while loop execution flow

Following image shows the execution flow of the while loop.
while loop in Java
The while statement evaluates the condition which is a boolean expression and it must return a boolean value.

If the boolean expression evaluates to true, then block of code in the while loop is executed.

The while statement continues testing the expression and executing its block until the expression evaluates to false. When condition controlling the while loop becomes false, loop is terminated and control passes to the next line of code immediately following the loop.

One thing to note about the while loop is that the conditional expression is evaluated at the top of the loop so the code with in the loop will not execute even once if the condition is evaluated to false in the beginning itself. That’s how while loop differs from do-while loop.

Java while loop examples

1- First example uses while loop to print numbers from 1 to 10.

Output

In the while loop condition (i <= 10) is evaluated in each iteration, it returns true till value of i is less than 10. Condition is evaluated to false when value of i becomes 10 and the loop terminates.
Value of i is incremented with in the while loop body so that the condition eventually evaluates to false.
2- Second example uses while loop to print numbers in reverse order 10 to 1.

Output

3- A while loop is executed repeatedly till the condition is true so you can implement an infinite loop by using a while(true) loop. Here is an example of while(true) loop in Java. You will need to manually terminate the code to come out of the loop.

4- Since a condition controlling the while loop is a boolean expression so you can use a boolean flag to control the loop. Following example shows another way to display numbers 1 to 10 using while loop and a boolean flag.

That’s all for the topic while Loop in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.