Friday, 5 January 2018

Example of For-each loop in Java


For-each loop is also array traversing technique like the do-while loop, for loop, while loop. It is commonly used to iterate over an array of Collections such as ArrayList and the LinkedList.


for (type variable : array_name) 
    statements using the variable;

This loop starts with the keyword for as a normal for loop start. But instead of declaring and initializing the counter variable of loop, we declare a variable whose data type is same as the base data type of array and then a semi colon which is followed by the array name. In the statements inside the for loop you can use directly loop variable you created rather than using an indexed array element.

For-each has some limitations due to which it is not best to use during the normal array traversal, which are given below:


1. For-each loop are not appropriate when you want to modify the array.
    Example: num=num*2; will change the num variable instead of modifying it in array.
2. This loop do not track the index of the array. Therefore, array index can not be obtained.
3. It iterates only in forward direction.
4. For-each loop is unable to process tow decision making statements at once such as checking if two numbers are equal or not.


import java.util.Scanner;

public class for_each{

        public static void main(String args[]){

               int[] runs_scored={59,90,45,356};

               System.out.print("\nTraversal using for-each loop: \n");
               for(int variable: runs_scored){

                     variable++;     //update the variable

                System.out.print("\nTraversal using normal for loop: \n");

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

                       //You can see in output that array is not modified