1
0

While Loop in Java

The while statement repeatedly executes a block of statements while a particular condition is true. Its syntax can be expressed as:

while(expression)
{
    statement(s);
}

The while statement evaluates the expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the result of the expression remains true. When the while expression evaluates to a false, the value of the loop is terminated and control is transferred to the statement following the while block.

Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:

Program to print numbers from 1 to 10 using while loop

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

You can implement an infinite loop using the while statement as follows:

while(true)
{
    statement(s);
}

Leave a Reply