while loop

The while loop repeats a statement or block while its controlling expression is true. Here is its general form:


while(condition) { 
   // body of loop 
}
  • The condition can be any Boolean expression.
  • The body of the loop will be executed as long as the conditional expression is true.
  • The curly braces are unnecessary if only a single statement is being repeated.

Here is a while loop that counts down from 10, printing exactly ten lines of "tick":

  
public class Main {
  public static void main(String args[]) {
    int n = 10;
    while (n > 0) {
      System.out.println("n:" + n);
      n--;
    }
  }
}  

When you run this program, you will get the following result:


n:10
n:9
n:8
n:7
n:6
n:5
n:4
n:3
n:2
n:1

The body of the while loop will not execute if the condition is false. For example, in the following fragment, the call to println() is never executed:

  
public class Main {
  public static void main(String[] argv) {
    int a = 10, b = 20;
    while (a > b) {
      System.out.println("This will not be displayed");
    }
    System.out.println("You are here");
  }
}
  

The output:


You are here

The body of the while can be empty. For example, consider the following program:

  
public class Main {
  public static void main(String args[]) {
    int i, j;
    i = 10;
    j = 20;

    // find midpoint between i and j
    while (++i < --j)
      ;
    System.out.println("Midpoint is " + i);
  }
}  

It generates the following output:


Midpoint is 15
Home 
  Java Book 
    Language Basics  

Statement:
  1. Simplest if statement
  2. If else statement
  3. switch statement
  4. while loop
  5. do-while statement
  6. for Loop
  7. for each loop
  8. break to Exit a Loop
  9. continue
  10. return statement returns from a method.
  11. Comments