Loops in Java

Loops are used to execute a block of code several number of times until some conditions are true. Following are the three types of loops in java:

  • for loop
  • while loop
  • do while loop

The for loop

The for loop is used to iterate over an array or list of items for a fixed number of times. The general form of the for statement can be expressed as follows:


for (initialization; termination; increment) {
    //statements here    
}
  • initialization — The initialization expression initializes the loop; it is executed once, as the loop begins.
  • termination — When the termination expression evaluates to false, the loop terminates.
  • increment — The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
Example

A program to print numbers from 1 to 10:


public class ForLoopExample1 {

    public static void main(String[] args) {

        for (int i = 1; i < 11; i++) {

            System.out.println(i);
        }
    }

}
Output
1
2
3
4
5
6
7
8
9
10

A program to iterate over an array using for loop:


public class ForLoopExample2 {

    public static void main(String[] args) {

        String[] foodsItems = {"Eggs", "Mango", "Potato", "Garlic",
                "Pineapple", "Ginger"};

        for (int i = 0; i < foodsItems.length; i++) {

            System.out.println("" + "Food item at foodsItems[" + i + "] = "
             + foodsItems[i]);

        }
    }

}
Output
Food item at foodsItems[0] = Eggs
Food item at foodsItems[1] = Mango
Food item at foodsItems[2] = Potato
Food item at foodsItems[3] = Garlic
Food item at foodsItems[4] = Pineapple
Food item at foodsItems[5] = Ginger

The enhanced for loop

The for loop also has another form of for loop referred to as the for-each loop or enhanced loop to work with arrays and collection. It was introduced in Java version 5.0. It can be used to make loops more compact and easy to read.

Example

public class EnhancedForExample {

    public static void main(String[] args) {

        String[] birdsArray = {"Pigeon", "Parrot", "Peacock", "Kiwi", 
                "Sparrow", "Kingfisher"};

        for (String bird : birdsArray) {

            System.out.println("Bird = " + bird);

        }
    }

}
Output
Bird = Pigeon
Bird = Parrot
Bird = Peacock
Bird = Kiwi
Bird = Sparrow
Bird = Kingfisher

The while loop

The while loop continually executes a block of statements until a particular condition is true. Its syntax can be expressed as:


while (expression) {
    // statements here
}

The while loop evaluates an expression that returns a boolean value. The while statement executes the statement(s) in the while block until the expression evaluates to true.

Example

A program to iterate over an array using the while loop:


public class WhileLoopExample {

    public static void main(String[] args) {

        String[] colorsArray = {"Green", "Blue", "White", 
                "Red", "Yellow", "Orange"};

        int index = 0;

        while (index < 5) {
            System.out.println("Color = " + colorsArray[index]);
            index++;
        }
    }

}
Output
Color = Green
Color = Blue
Color = White
Color = Red
Color = Yellow

The do while loop

The Java programming language provides a do-while loop. The do-while evaluates its expression at the bottom of the loop instead of the top and the statements within the do block are always executed at least once even if the condition is false.


do {
    // statements here
} while (expression);
Example

A program to iterate over an array atleast once even if the loop condition is false:


public class DoWhileLoopExample {

    public static void main(String[] args) {

        String[] colorsArray = {"Green", "Blue", "White", 
                "Red", "Yellow", "Orange"};

        int count = 0;

        do {
            System.out.println("Color = " + colorsArray[count]);
            count++;

        } while (count < 1);
    }

}
Output
Color = Green

The statement inside do block is executed first and then the expression is evaluated.