For-each loop in Java

For-each loop in Java


For-each loop is a useful array traversing technique introduced

in Java5 that simplifies the process of terating over an array or

a Collections class (e.g., ArrayList). It's similar to other loops

like for loop, while loop, and do-while loop, but with some

differences in syntax and behavior.


To use a for-each loop, you need to 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. In the loop body, you

can use the loop variable you created rather than using an

indexed array element.


Here's the syntax of a for-each loop:


for (type var : array) {

    statements using var;

}

This syntax is equivalent to the traditional for loop:



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

    type var = arr[i];

    statements using var;

}


Here's an example of using a for-each loop to find the maximum value in an array of integers:


public static int maximum(int[] numbers) { 

    int maxSoFar = numbers[0];

    for (int num : numbers) {

        if (num > maxSoFar) {

            maxSoFar = num;

        }

    }

    return maxSoFar;

}

Output: The highest score is 132


Although for-each loops are a convenient way to iterate over an array or a Collection, they have some limitations:


  • They are not appropriate when you want to modify the array.
  • They do not keep track of the index of the current element.
  • They only iterate forward over the array in single steps.
  • They cannot process two decision-making statements at once.
  • They have some performance overhead over simple iteration.


Here's an example to compare the performance of using

for-each loop and other types of loops:


public static void main (String[] args) {

    List<Integer> list = new ArrayList<>();

    long startTime;

    long endTime;

    for (int i = 0; i < 1000000; i++) {

        list.add(i);

    }

    // Type 1

    startTime = Calendar.getInstance().getTimeInMillis();

    for (int i : list) {

        int a = i;

    }

    endTime = Calendar.getInstance().getTimeInMillis();

    System.out.println("For each loop :: " + (endTime - startTime) + " ms");

    

    // Type 2

    startTime = Calendar.getInstance().getTimeInMillis();

    for (int j = 0; j < list.size(); j++) {

        int a = list.get(j);

    }

    endTime = Calendar.getInstance().getTimeInMillis();

    System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");

    

    // Type 3

    startTime = Calendar.getInstance().getTimeInMillis();

    int size = list.size();

    for (int j = 0; j < size; j++) {

        int a = list.get(j);

    }

    endTime = Calendar.getInstance().getTimeInMillis();

    System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms");


    // Type 4

    startTime = Calendar.getInstance().getTimeInMillis();

    for(int j = list.size()-1; j >= 0; j--) {

        int a = list.get(j);

    }

    endTime = Calendar.getInstance().getTimeInMillis();

    System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");

}


Previous Post Next Post