Java while loop statement

Introduction

The Java while loop repeats statements based on its controlling expression.

Here is its general form:

while( condition) {  
   // body of loop  
} 

The condition can be any Boolean expression.

The body of the loop is executed if the conditional expression is true.

When condition becomes false, control passes to the next line of code following the loop.

The curly braces are not required if only a single statement is being repeated.

The following code shows a while loop that counts down from 10, printing exactly ten lines of "tick":

// Demonstrate the while loop.
public class Main {
  public static void main(String args[]) {
    int n = 10;//from  w w w.  j a v a2 s  . c  o m

    while(n > 0) {
      System.out.println("tick " + n);
      n--;
    }
  }
}

Java while loop checks its condition at the top of the loop, the loop body will not run if the condition is false to begin with.

For example, in the following fragment, the call to println() is never executed:

int a = 10, b = 20;  
            
while(a > b){
  System.out.println("This will not be displayed"); 
}

The body of the while loop can be empty.

; represents an empty statement in Java.

For example, the following code calculates the middle value between two integer values.

The value of i is incremented, and the value of j is decremented.

// The target of a loop can be empty. 
public class Main {
  public static void main(String args[]) {
    int i, j;/* w  w w.j  av a2 s .c  om*/

    i = 100;
    j = 200;

    // find midpoint between i and j
    while(++i < --j) ; // no body in this loop

    System.out.println("Midpoint is " + i);
  }
}



PreviousNext

Related