It is used to execute a set of statements repeatedly as long as the condition is true. This loop checks the condition before executing the statement inside while loop.
Syntax
while(condition) { //code to be executed }
Flowchart of while loop
public class Example { public static void main(String args[]) { int i = 1 while(i<=10) { System.out.println(2*i); i++; } } }
Output
2 4 6 8 10 12 14 16 18 20
By passing true in while loop you will get infinite while loop.
Syntax
while(true) { //code to executed }
Example
public class Example { public static void main(String args[]) { while(true) { System.out.println("This is infinite while loop."); } } }
Output
This is infinite while loop. This is infinite while loop. This is infinite while loop. This is infinite while loop. ctrl+c
Press ctrl+c to exit infinite while loop.