While loop
The next form of loop is the while-loop. The while-loop declaration is syntactically simpler than the for-loop: it specifies a condition than must remain true for the loop to continue processing:
public static void main(String[] args) {
int i = 0;
while (i < 10) {
System.out.println("The number is "+i);
i++;
}
}
In many ways while-loops are similar to for-loops. The three parts of the for-loop definition still exist, but two of the parts are declared outside the loop declaration:
• The declaration of the variable that will control iteration needs to occur before the loop is declared. In this example the variable i is declared on the first line of the method.
• The boolean expression to determine whether the loop should continue occurs inside the loop declaration. In this case the expression is i < 10.
• The modification of the counter variable must occur inside the loop. In this case the variable is modified with the following statement: i++.
If the body of the loop did not augment the i variable, the loop could never stop (an infinite loop would be created). The Java compiler cannot detect infinite loops, and therefore they are a common source of run-time bugs.
Most other features of while-loops are the same as for-loops. They execute a block of code with each iteration, they can use the continue and break keywords to control execution, and they can be nested inside one another.
Do-while loops
With while loops it is possible that the code inside the while loop will never execute. This will occur when the initial evaluation of the boolean expression is false, for instance:
while (i > 0) {
This leads on to the final type of loop, the do-while loop.
The only difference between a do-while loop and a while loop is that a do-while loop is guaranteed to execute at least once, even if the boolean expression evaluates to false the first time it is evaluated. For this reason, the boolean expression appears after the body of the loop:
public static void main(String[] args) {
int i = 0;
do {
System.out.println("The number is "+i);
i++;
} while (i < 10);
}
If you try changing both this loop, and the while-loop to use the expression i < 0, and you will notice that the do-while loop still executes once.
In honesty, I can count on one hand the number of times I have used a do-while loop, but it is important to know they exist, and occasionally you will find a use for them.