Java for-each loop

Before proceeding further, you have to knowledge of

  • For loop
  • Array
  • Collection

Java for each loop:

It is also called enhanced for loop

  • It is another form of for loop
  • It is mainly used to traverse the array or collection in java
  • It reduces the code complexity and makes it code more readable

Syntax of for loop:

for(data_type item : collections) {
    //body of for each loop
}

Working of for loop:

Let’s see example first

//An example of Java for-each loop  
class ForEachExample1{  
  public static void main(String args[]){  
   //declaring an array  
   int num[]={12,13,14,44};  
   //traversing the array with for-each loop  
   for(int i:num) {  
     System.out.println(i);  
   }  
 }   
}
12
12
14
44

As you can see in the example num is an array of integer which contain some number.

In for each loop, we pass the array of integer num then for each loop traverse the array and store the array item in a variable i

And execute the body of for each loop

Note: it is recommended to use for each loop with array or collection. Because it makes the code readable


Advantage:

  • It is easy
  • It reduces the possibility of error in code
  • Make code more readable

Disadvantage:

  • It does not work on an index basis
  • We can’t skip any element of array and collection.
  • it can’t work in reversed order

Example: traversing array list using for each loop

import java.util.*;  
class ForEachExample2{  
  public static void main(String args[]){  
   //Creating a list of elements  
   ArrayList<String> list=new ArrayList<String>();  
   list.add("rahul");  
   list.add("sachine");  
   list.add("monika");  
   //traversing the list of elements using for-each loop  
   for(String s:list){  
     System.out.println(s);  
   }  
  
 }   
}  
rahul
sachine
monika



SHARE THIS PAGE





Important Link