|
The while loop is good when you want to execute a block based on some condition. In while loop you probably don’t know exactly how many times a block will be executed as it will based on some condition. The general format of while loop is:
while(booleanExpresion) {
[Statements;]
}
The booleanExpresion is evaluated once at the beginning of the loop and again before each further iteration of the statements. Similar to the if statement, the while statement should use a pair of curly brackets for better readability. The curly brackets enclose the statements to be executed when the condition is true. The Following code is a simple example that generates even numbers between 1 to 100 using a while loop.
int number = 0;
while (number <= 100) {
System.out.println(number);
number = number + 2;
}
The curly brackets are optional. But, if they are absent, only the first statement after the while() is executed when the condition in it is true. Note that the condition is tested for each iteration. If the condition is false for the very first iteration, the statements in the while loop are never executed. For instance, in the previous example, if the number is 102 at the start of the loop, the statements in the loop will never be executed. Therefore, the following code will not print anything if executed:
int number = 102;
while (number <= 100) {
System.out.println(number); // never executed
number = number + 2; // never executed
}
This fact is the main difference between the way while and do-while loop work.