Java for-each Loop: Syntax and Usage Explained
☰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
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[]){ ArrayListlist=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 . . .