The For Each Loop in Java

The For Each Loop in Java

Let us talk about For Each Style loop in Java. One of the most beautiful feature of the Java core.










import java.util.*;
class ForEach
{
    public static void main(String args[])
    {
   
    Scanner s=new Scanner(System.in);

    int n;

    System.out.println("Enter the no.of elements");
    n=s.nextInt();

    int[] a=new int[n];

    System.out.println("\nEnter the elements");

        for(int i=0;i<a.length;i++)
        {
        a[i]=s.nextInt();
        }

    System.out.println("\nPrinting the elements");
       
        for(int i:a)
        {
            System.out.println(i);
        }
    }
}

Sample Output


Enter the no.of elements
5

Enter the elements
1
2
3
4
5

Printing the elements
1
2
3
4
5


Explaining the Loop

for(int i:a): Every element in the array a starting from the 0th index is represented by i and the loop rotates till the end of the array increasing the index. For a better understand, this loop is much similar to..
for(int i=0;i<a.length;i++). Here a[i] is represented by i (in for each style). 

In the for each loop, when the loop is executed for the first time the value of i is equal to the value of the element in the 0th index in the array. The second time, the value of i is equal to the value of the element in the 1st index in the array and so on, this continues till the end of the loop i.e. till the index is (n-1) where n is the no.of elements in the array.

From this we can clearly say that for each loop is different from the normal for loop in syntax. It goes in increasing order of the indexes. It is not be customizable. It can also be used in variable arguments. This type of loop can also be used on the for objects.

No comments: