For each loop in Java

In this tutorial, we are going to learn about one of the most famous looping techniques, For each loop in Java that is also known as enhanced for loop. This loop is a control flow statement used for traversal of an array or a collection. In Java it was firstly introduced in JDK 1.5.

It’s common syntax is: –

for(return datatype : the collection or the array name){
    //Code You Want To Write;
}

For each loop Java Implementation

Now we are gonna create a String Array containing some random String values. So, we will be using for each loop to traverse through that array and print its value.

CODE: –

public class Main
{
  public static void main(String[] args) {
    String array[]={"ASD","ZXC","QWE","RTY","GHJ"};
    for(String i:array){
        System.out.println(i);
    }
  }
}

Code Output: –

ASD
ZXC
QWE
RTY
GHJ

We saw that in this loop we did not even mention the length of the array and we traversed all the elements. The syntax is also quite simple just the return type and the name of the array that is being traversed.

Now we are creating a list(collection) of integers and we are going to add the integers in the list and will print it’s sum.

CODE: –

import java.util.*;
public class Main
{
  public static void main(String[] args) {
    List<Integer> lst=new ArrayList<Integer>();
    lst.add(10);
    lst.add(20);
    lst.add(30);
    lst.add(40);
    int sum=0;
    for(int i:lst){
        sum+=i;
    }
    System.out.println("The sum of the List is: "+sum);
  }
}

Code Output: –

The sum of the List is: 100

Some bulletin points for using for each loop: –

  1. We Can’t use this loop for backward propagation i.e we cannot go from back to front in this. For this first reverse the array then we can propagate backward.
  2. It is less prone to error due to its easy syntax.
  3. No use of indexing is there.

Also read: –

Exit from a loop in Java with

Leave a Reply

Your email address will not be published. Required fields are marked *