Loops
In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.
While Loop Example
The while loop loops through a block of code as long as a specified condition is true:
​
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:
Do-While Loop Example
The do-while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
​
The example below uses a do-while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
For Loop Example
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. The outline of a for loop is shown below.
​
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}//end for loop
​
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
​
​