Java While Loop

While loop in java is used to execute a block of code multiple times, until a condition becomes true. Unlike for loop, there is no initialization and increment/decrement step in while loop.

While loop is preferred when the number of iteration is not fixed.

Here is the syntax of while loop in java
while(condition) {
    /* code to be executed */
    statement(s);
}
  • condition : Condition expression is a boolean expression which gets evaluated each time before control enters while loop's code block. If condition expression evaluates to true, then code block inside while loop gets executed otherwise it will terminate while loop and control goes to the next statement after the while loop.

  • statement : It is the set of statements which gets executed once in every iteration. While loop can contain any number of statements including zero statements.

Java While Loop Statement Control Flow Diagram
Points to Remember about While Loop
  • The condition in while loop is a boolean expression.

  • Unlike for loop, there is no initialization and update statements.

  • Opening and Closing braces are not required for single statement inside while loop code block.
    For Example:
        while(i < 100)
            sum+= i;
  • We can also use infinite while loops like while(1), which will never terminate. You should add terminating condition using break statement in order to terminate infinite while loop.
    For Example:
        while(1) {
            if(.....){
                break;
            }
        }