While Loop

Loop constructs are used to iterate a piece of code again and again until specified condition is true. for example if want to print "hello world" message 10 times, without loop constructs we have to write printing statemnt 10 times. In order to simplifying the iteration process, loop constructs are introduced. Loop in java are same as in c or c++. In java we have while, do-while, for and for each.


Syntax of while loop

    while ( Condition )
{
Statement1;
Statement2;
...........
...........
Statementn;
}

While loop condition are evaluated first, if it is true then all the statements present in while loop are executed. After executing all statement, again condition of while loop will be checked. if again condition is true then again all statements will be executed. It will be continued until condition is true. When condition become false then while loop execution will be over.



In while loop condition has to be specified, otherwise compiler will generate an error.

Example :


// file: even.java
// www.jgyan.com
class even
{
public static void main(String ...arg)
{
int i=2;
while(i<=100)
{
System.out.println(i);
i=i+2;
}
}
}


In above program while loop execute until i is less than or equal to 100. In loop value of 'i' is also getting increased. If we won't increase the value this loop will execute forever. In case of while loop if condition is false loop's statement won't execute.


Important ! Condition part can't be left blank in while loop