Java while Loop

In this chapter you will learn:

  1. What is Java while loop
  2. How to use the basic Java While Loop
  3. Note for Java while Loop
  4. Example - Java while loop
  5. Example - while condition
  6. Example - while loopbody

Description

The while loop repeats a statement or block while its controlling condition is true.

Syntax

Here is its general form:


while(condition) { 
   // body of loop 
}

Note

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

Example

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;//from  w w w  .  j  a v a  2s  . c  om
    while (n > 0) {
      System.out.println("n:" + n);
      n--;
    }
  }
}

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

Example 2

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");
    }/*  w ww.  j a  va2  s  .c o  m*/
    System.out.println("You are here");
  }
}

The output:

Example 3

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;//  w  w  w . java  2  s  . com
    i = 10;
    j = 20;

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

The while loop in the code above has no loop body and i and j are calculated in the while loop condition statement. It generates the following output:

Next chapter...

What you will learn in the next chapter:

  1. Why do we need Java do while loop
  2. Syntax for Java do while loop
  3. Example - How to use do-while statement
  4. How to create a simple help menu with while loop and switch statement
Home »
  Java Tutorial »
    Java Langauge »
      Java Statement
Java if Statement
Java if else Statement
Java if else ladder statement
Java nested if statement
Java switch Statement
Java for loop
Java for each loop
Java while Loop
Java do while loop
Java break statement
Java continue statement
Java Comments
Java documentation comment(Javadoc)