Java while loop



While Loop statement in Java : Iterative Statement (Loop Control Statement)

  1. In java “while” is iteration statements like for and do-while.
  2. It is also called as “Loop Control Statement“.
  3. While Statement” repeatedly executes the same set of instructions until a termination condition is met.
  4. While loop is Entry Controlled Loop because condition is check at the entrance.
  5. If initial condition is true then and then only control enters into the while loop body
  6. In for loop initialization,condition and increment all three statements are combined into the one statement , in “while loop” all these statements are written as separate statements.
  7. Conditional Expression written inside while must return boolean value.

[468×60]

Flow Diagram :

while loop in java programming language

Syntax :

while(condition) {
  // body of loop
}
  • The condition is any Boolean expression.
  • The body of the loop will be executed as long as the conditional expression is true.
  • When condition becomes false, control passes to the next line of code immediately following the loop.
  • The curly braces are unnecessary if only a single statement is being repeated.

[336×280]

Live Example :

class WhileDemo {
    public static void main(String[] args){
        int cnt = 1;
        while (cnt < 11) {
            System.out.println("Number Count : " + cnt);
            count++;
        }
    }
}

Legal Ways of Writing While loop :

While Loop : Single Statement Inside Loop Body

class WhileDemo {
    public static void main(String[] args){
        int cnt = 1;
        while (cnt < 11)
            System.out.println("Number Count : " + cnt++);
    }
}

Single Statement is a part of While Loop as there is no opening and closing curly braces.
Suppose we want to embed multiple statements as a part of while loop body then we can put all the statements in a block.

While Loop : Boolean Condition

class WhileDemo {
    public static void main(String[] args){
        boolean b1 = true;
        while (b1)
            {
            System.out.println("Number Count : " + cnt);
            cnt++;
            if(cn==5)
               b1 = false;
            }
    }
}

We can put single variable as while condition but it must be of type boolean. thus the following statement will cause compile time failure –

int b1 = 12;

while (b1)
  {
  System.out.println("Number Count : " + cnt);
  cnt++;
  if(cn==5)
      b1 = 1;
  }

While Loop with no body

class NoBody {
  public static void main(String args[]) {
    int i, j;

    i = 10;
    j = 20;

    while(i < j);  // no body in this loop
    {
    System.out.println("Out of the Loop");
    }

  }
}

*Note : Semicolon after while condition is perfectly legal.