exampracticeonline.com
while loop

What is loop?

Loop is used to iterate or traverse a set of statements repeatedly until a particular condition is satisfied.

A loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

While loop in java

A java while loop is used to iterate a set of statements until given condition is true. 

While loop code flow diagram

4

How while loop works?

While loop follow below steps:

  1. First condition evaluated in while loop.
  2. If condition return true then code inside while loop executes and controller again goes to check condition.
  3. If condition return false then while loop skip and next code executes.

While loop syntax

While loop syntax is -

while(boolean_expression) {
   // Statements
}

Here boolean_expression can be single condtion or a group of condition that can return a boolean value (true or false). Inside statements execute only if boolean_expression return true. 

Type of while loop

Java have two types of while loop -

  1. Limited loop
  2. Infinite loop

Limited loop

Limited loop have a condition. When this condition return false then while code execution stops and jump to next code.

Example - Below code have a limit of 5 and after 5 iteration while loop not executes. 

public class WhileLoop {  

          public static void main(String[] args) {  

                  int count=1;  

                  while(count<=5) {  

                           System.out.println("value of count : "+count);  

                            count++;  

                  }  

          }  

}  

Output - 

value of count : 1
value of count : 2
value of count : 3
value of count : 4
value of count : 5

Infinite loop

Infinite loop would never end because while condition will never return false always return true.

Example - Below code would never end.

public class WhileLoop {  

          public static void main(String[] args) {  

                  int count=1;  

                  while(count>0) {  // this condition never false it would retrun true everytime. It just like a while(true)

                           System.out.println("value of count : "+count);  

                            count++;  

                  }  

          }  

}  

Output - 

value of count : 1
value of count : 2

-- infinite time