Java While Loop

To iterate some statements multiple times we basically use the concept of loop. There are few kinds of loop in java like for loop, while, do while loop, foreach loop etc.

Today we are going to talk about Java while loop.

# Java While Loop

When we don't know how many times exactly we want to loop through a block of code we use java while loop.

# Java while loop syntax:


while(condition){
      //statement to execute
      iteration (increment/decrement);
    }
 

Condition: The condition can be any boolean expression. The statement inside the loop will be executed till the condition is true. When it is false the loop will be terminated and go to next line immediately. You can omit the curely brackets if only a single statement is being repeated.

Loop control variable: it should be declared first that will be checked by conditional expression.

Iteration: it is an increment or decrement portion that is also dependent on the condition.

# Simple program to demonstrate while loop in java


public class Main{
  public static void main (String[] args) {
    
    //initial variable
    int x = 1; 
    int y = 10
    while( x < 10){
      //statement to be executed
      System.out.print(x +" ");
      
      //iteration
      x++; //increment by one
    }
    System.out.println(" ");
    while(y > 0){
      //statement to be executed
      System.out.print(y +" ");
      
      //iteration
      y--; //decrement by ine 
    }
  }
}
/**
 * Output
 * 1 2 3 4 5 6 7 8 9 10
 * 10 9 8 7 6 5 4 3 2 1
 */
 

# Another example of while loop


public class Main{
  public static void main (String[] args) {
    int x = 10; 
    int y = 20; 
    
    while(x < y){
      System.out.print(x +", ");
      x++;
    }
    
    //but there is no output
    while(x > y){
      System.out.println(x); //why no output? explains below
      x++;
    }
  }
}
/**
 * Output: 
 * 10
 * displays nothing for the second while
 */

**Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with. For this reason, in the above second while fragment, the call to println( ) is never executed.

Note: Don't forgot to set the step of iteration. Otherwise the loop will never terminate.