If we want to run a specific statement more than once in a loop, we need another method. To do this, java comes with another couple of keywords, while and for. The while statement is somewhat easier to use. It needs only one bool argument to determine if it should continue to execute. This statement is somewhat like the if statement, only that it returns to the top of the while statement when it’s done
with its evaluations.

The syntax of a while loop is :

while(Boolean_expression) {
// Statements
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value. When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true. When the condition becomes false, program control passes to the line immediately following the loop.

Flow Diagram:

while loop

Here, key point of the while loop is that the loops might not ever run. When the expression is tested and the result is false, the loops body will be skipped and the first statement after the while loops will be executed.

Example:

public class Test {
public static void main(String args[])
{
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " +
x );
x++;
System.out.print("\n");
}
}
}

This will produce the following result:

Output:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

To know about what is loops in java and loops control statements see our article named Loops and Loops Control Statements in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top