Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met. A loop statement allows us to execute a statement or group of statements multiple times.
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for loop is useful when you know how many times a task is to be repeated.
The syntax of a for loop is –
while Loop
A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop is –
Here, a key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
do while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Following is the syntax of a do...while loop –
Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops: