Java for-each Loop: Syntax and Usage Explained

Rumman Ansari   Software Engineer   2024-10-17 10:45:26   34010  Share
Subject Syllabus DetailsSubject Details 6 Program Login to Open Video
☰ TContent
☰Fullscreen

Table of Content:


For-each loop

  • The for-each loop introduced in Java5.
  • It is mainly used to traverse array or collection elements.
  • The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
  • It works on elements basis not index.
  • It returns element one by one in the defined variable.
  • It is easier to use than simple for loop because we don't need to increment value and use subscript notation.

Syntax


for(Type var:array){  
    //code to be executed  
}  
 
or

for(data_type variable : array | collection){  
    //code to be executed  
}    

Java For-Each Loop Flowchart

Java For-Each Loop Flowchart
Figure: Java For-Each Loop Flowchart


Example of for each Loop

/*
Demonstrate the for each loop.
save file "ForEachExample.java".
*/

public class ForEachExample {
public static void main(String[] args) {
    int array[]={10,11,12,13,14};
    for(int i:array){
        System.out.println(i);
    }
  }
}
 

Output:

10
11
12
13
14
Press any key to continue . . .
 

Example of for each Loop

/*
Demonstrate the for each loop.
save file "ForEachExample.java".
*/

import java.util.*;
class ForEachExample{
  public static void main(String args[]){
   ArrayList list=new ArrayList();
   list.add("Rumman");
   list.add("Jaman");
   list.add("Student");

   for(String s:list){
     System.out.println(s);
   }

 }
}
 

Output:

Rumman
Jaman
Student
Press any key to continue . . .
 

MCQ Available

There are 2 MCQs available for this topic.

2 MCQ