These are the statements that enable us to execute a particular block repeatedly until a given condition returns false. Java supports While, For and Do-While statements.
While
It runs a particular block until a control expression becomes false. As and when the condition gets false, control passes to the statement that is immediately after the loop.
Syntax:
while(condition) { //block }
Do-while
In this, first loop body is executed and then after the condition is checked. It is a special loop in which control expression is checked after the execution of the block. The loop body runs at least once, no matter what condition is.
Syntax:
do{ //body }while(condition)
For
It is a type of loop where the control variable, condition, and iteration are all put together at a single place.
A control variable acts as a counter and is executed once. After that, the condition is evaluated if it is true the loop body would be executed otherwise, it gets terminated. Lastly, the iteration portion is executed. In this control variable is incremented or decremented. The incremented or decremented value is checked with the condition and if it returns true, the loop body would be executed. It keeps iterating until the condition returns false.
Syntax:
for(control_variable;condition;increment or decrement) { //body }
There is an advanced version of For which is referred to as For-each. However, it doesn’t require any keyword to declare this statement.
For-each is used to iterate through a collection of objects until all the elements are iterated.
for(type element_name:collection) { //body }
Java program to demonstrate the working of the iteration statement
Program:
public class IterationStatement { public static void main(String[] args) { int i=0; int control_variable; int arr[] = {1,2,3,4}; while(i<5) { System.out.println("I am iterating using While Loop "+i+" time "); i++; } // do while i=0; do{ System.out.println("I am iterating using Do-While Loop "+i+" time "); i++; }while(i<5); // For loop for(control_variable =0;control_variable<5;control_variable++) { System.out.println("I am iterating using For Loop "+control_variable+" time "); } // For-Each for(int element:arr) { System.out.println("I am iterating using For-each Loop "+element+" time "); } } }
Output: