Friday 26 June 2015

for each loop in java


What is for each loop?
for each loop in java is the enhanced version of for loop. It is introduced from JDK 5. It is used to iterate all elements of an array or Collection.

Syntax:

for ( data-type variableName :  array or collection )
{
    //statements
}

Consider the following program:

public class ForEachLoop
{
    public static void main(String[] args)
    {
        int[] array ={ 1, 2, 3, 4, 5 };
        System.out.println("Array elements: ");

        for(int element: array)
               System.out.print(element+"  ");

    }
}


Write the above program in Notepad and save it as ForEachLoop.java 
Compile and run it to get the following output:

Array elements: 
1  2  3  4  5

the loop for(int element: array)
fetches the elements of array and assign it to variable element so we can use element to access the elements of array

Consider the following program to access elements of multi-dimensional array


public class ForEachLoop
{
    public static void main(String[] args)
    {
     int[][] array ={ {1, 2, 3, 4,},{ 5,6,7,8} }; //array with 2 rows and 4 columns
        System.out.println("Array elements: ");
        for(int[] row: array)
            for(int element: row)
               System.out.print(element+"  ");
    }
}

Write the above program in Notepad and save it as ForEachLoop.java 
Compile and run it to get the following output:

Array elements: 
1  2  3  4  5  6  7  8

the loop for(int[ ] row: array)
fetches one row of array and assign it to variable row so we can use row to access one row(or one dimensional array) of array

the loop for(int element: row)
fetches the elements of row and assign it to variable element so we can use element to access the elements of row

No comments:

Post a Comment