While Loop In Java

In this page we will learn about What is While loop in Java?, Syntax of while loop in java, two part in while loop, Example 1 of while loop in java, Example 2 of while loop in java, What is Java Infinitive While Loop?, Syntax of Infinitive While Loop, Example Infinitive While Loop.


What is While loop in Java?

To iterate a part of the program, the java while loop is operated. If the number of iteration is not stabilized, it is suggested to use while loop.

while loop in Java

Syntax of while loop in java:


  while(condition) {  
    //statement or code to be executed
    //increment or decrement  
    }      

There are mainly two part in while loop.

  1. Condition: Condition is an expression which is tested. If the expression is true, the loop body will be executed and control goes to indcrement or decrement part. When the expression becomes false, we exit the while loop.
  2. Incr/Decr:Each iteration loop body is executed, this expression updates (increments or decrements) loop's variable.

Here, the important thing about while loop is that, sometimes it may not even execute. If the expression to be tested outcomes into false, the loop body is skipped and first statement after the while loop will be executed.

Example 1 of while loop in java:


  public class WhileLoop {  
    public static void main(String[] args) {  
      //Code of Java for loop 
     int i = 1; 
     while(i<=10){  
        System.out.println("Hello From Java");
        i++;//incremented by 1 
      }  
    }  
  }  

Output:

  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java
  Hello From Java

Example 2 of while loop in java:


  public class WhileLoop {  
    public static void main(String[] args) {  
      //Code of Java for loop 
     int i = 1; 
     while(i<=5){  
        System.out.println(i);
        i++;  
      }  
    }  
  }  

Output:

  1
  2
  3
  4
  5

What is Java Infinitive While Loop?

If you finish true in the while loop, it will be infinitive while loop.

Syntax of Infinitive While Loop:


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

Example of Infinitive While Loop:

  
    public class NastedWhileLoop {  
      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