While Loop in java

Java while loops statement allows to repeatedly run the same block of code, until a condition is met.
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop or
while loop is most basic loop in Java. It has one control condition, and executes as long the condition is true. The condition of the loop is tested before the body of the loop is executed, hence it is called an entry-controlled loop.

syntax:

While (condition)
  {
statement(s);
Incrementation;
 }
flowchart of while loop

Example

public class Sample {
public static void main(String args[]) {
    /* local variable Initialization */
int n = 1, times = 4;

   /* while loops execution */
while (n <= times) {
System.out.println("while loops in java:" + n);
 n++;
     }
    }
   }

Output

while loops in java: 1
while loops in java: 2
while loops in java: 3
while loops in java: 4

Infinitive While Loop in Java

If you pass true in the while loop, it will be infinitive while loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.

syntax:

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

example

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

Output

infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

do-while Loop in Java

The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute theloop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.

syntax:

do {  
  //code to be executed  
  } while(condition);  
flowchart of do-while loop

example

public class Sample {
public static void main(String args[]) {
  /* local variable Initialization */
int n = 1, times = 0;
    /* do-while loops execution */
do  {
System.out.println("do while loops in java:" + n);
n++;
 } while (n <= times);
    }
   } 

Output

do while loops in java: 1

Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

syntax:

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

example

public class DoWhileExample2 {  
public static void main(String[] args) {  
do{  
System.out.println("infinitive do while loop");  
  }while(true);  
  }  
  }   

Output

infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.