Java - Statement while Statement

What is while loop?

A while statement is a loop statement.

It executes a statement repeatedly as long as a condition is true.

Syntax

The general form of a while-loop statement is

while (condition-expression)
        Statement

The condition-expression must be a boolean expression.

The statement can be a simple statement or a block statement.

  • The condition-expression is evaluated first.
  • If it returns true, the statement is executed.
  • Then, the condition-expression is evaluated.
  • If it returns true, the statement is executed.
  • It loops until the condition-expression returns false.

The condition-expression in a while-loop statement is not optional.

The body of a while loop may not be executed even once if the condition-expression evaluates to false for the first time.

To make a while statement infinite loop, use the boolean literal true as the condition-expression.

while (true)
   System.out.println ("This is an infinite loop");

Some for-loop statements can be converted to a while-loop statement.

The conversion between a for-loop and a while-loop statement is shown below.

A for-loop statement:

for (initialization; condition-expression; expression-list)
      Statement

Equivalent while-loop Statements:

Initialization
while (condition-expression) {
        Statement
        Expression-list
}

Related Topics

Example

Exercise