«Back to Home

Core Java

Topics

For Each Loop In Java

for-each loop
 
It is a Java 5 feature. For each loop or enhanced for loop is used to traverse an array or collection in Java. It is simple to use than for loop because in it, we don’t need to increment the value and use subscript notation.
 
It works on the elements basis and not index basis. It returns an element one by one in the defined variable.
 
Syntax

for(Type var: array)
{
// statements or code.
}
 
Let’s see an example, given below.
 
Code
  1. public class ForEachExm {  
  2.     public static void main(String[] args) {  
  3.         int arr[] = {12345};  
  4.         for (int s : arr) {  
  5.             System.out.println("Array:" + s);  
  6.         }  
  7.     }  
  8. }  
71

Output

73

The Nested loop

Java also allows to be nested i.e., one loop is declared inside another loop.
 
Let’s see an example, given below.
 
Code
  1. public class NestedLoopExm {  
  2.     public static void main(String args[]) {  
  3.         for (int i = 1; i < 11; i += 1) {  
  4.             for (int j = 0; j < 9 - i / 2; j++) {  
  5.                 System.out.println("");  
  6.             }  
  7.             for (int j = 0; j < i; j++) {  
  8.                 System.out.println("*");  
  9.             }  
  10.             System.out.println("\n");  
  11.         }  
  12.         System.out.println("");  
  13.     }  
  14. }  
74

Output

75

Summary

Thus, we learnt “For each loop” or enhanced for loop is used to traverse an array or collection in Java and also learnt how to use it.