Java: while loop

The Java while loop is a control flow statement, used to iterate a part of the program several times. It preferred when the number of iteration is not fixed.

See Also: Java: Types of Looping Statements

Syntax:


while(condition){  
//code to be executed  
}

Flow chart for while loop

while loop flow chart

Example: Print even numbers between 1 to 20.

This is the same example written in for loop also in the previous post.

class WhileLoopExample {
public static void main(String[] args) {
   System.out.println("Even Numbers between 1 to 20 :");
   int i=1;
   while(i<=20){
     // If modulus of number after devision 2 is 0 then even number
     if (i % 2 == 0) {
            System.out.println(i);
       }
      i++;
     }
   }
}

Output:


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Infinitive While Loop

If you pass true or condition satisfied always as true in the while loop, it will be execute infinitive times.

Syntax:


while(true){  
//code to be executed  
}  

Example: while infinite loop

public class WhileExample2 {
public static void main(String[] args) {
    while(true){
        System.out.println("FacingIssuesOnIT”);
    }
}
}

Output:


FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
FacingissuesOnIT
.................
..............
............

ctrl+c

Note: Use press ctrl+c to exit from the program otherwise that will continue the print “FacingIssuesOnIT” statement.