Looping statements

Looping statements can execute a block of code as long as a specified condition is reached

The different looping statements available in java

The while statement

The while statement continually executes a block of code while a particular condition is true

Syntax

while (condition) {
  // code block
}

 

Program:

public class Usecase {
    public static void main(String[] args) {
        int x = 0;
        while (x < 5) {
            System.out.println(x);
            x++;
        }
    }
}

 

do-while statement

do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once

Syntax

do {
       // code block
} while (expression);

 

Program:

public class Usecase {

    public static void main(String[] args) {
        int x = 0;
        do {
            System.out.println(x);
            x++;
        }
        while (x < 5);
    }
}

 

For statement

> The for statement provides a compact way to iterate over a range of values and it repeatedly loops until a particular condition is satisfied

> The initialization expression initializes the loop once it is executed as the loop begins.

> When the termination expression evaluates to false, the loop terminates.

> The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

Syntax

for (initialization; termination;
     increment) {
    // code block
}

 

Program:

public class Usecase {
    public static void main(String[] args) {
        int x = 0;
        for (int i = 1; i < 11; i++) {
            System.out.println("Count is: " + i);
        }
    }
}

 

For-each Loop

for-each loop is used to iterate the array/collection class. It is referred to as for each because it iterates through each element of the array.

It uses the same keyword for like for loop, Instead of declaring and initializing a loop counter variable, we should declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name

Syntax

for (type var : array)
{
    statements using var;
}

Program:

public class SampleLoop {
    public static void main(String[] args) {
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        // foreach loop
        for (char item : vowels) {
            System.out.println(item);
        }
    }
}

Output:

a
e
i
o
u

 

Limitations

> It is not appropriate when you want to modify the array

> It does not keep track of the index. So we cannot obtain an array index using the For-Each loop

> It only iterates forward over the array in single steps

> It cannot process two decision-making statements at once

 

Related Tutorials

Map