web analytics

Java While Loop

When we want to execute a block of code again and again until a condition remains true we can use loops in java.
There are four types of loops in java

Java while loop

Java while loop executes the code block until the loop condition remains true.

Syntax


while(condition){
// statements of code to be executed.
}

Example:

Following is an example of loop. It will will execute the statement again and again until the value of index remains less than ten.


int index = 1;
while (index < 10) {
System.out.println("Value of index is :"+index);
index++;
}

Important: Loop will never terminate if variable used in condition remains constant. Therefore it should be incremented / decremented according to situation.