Java - For Each Loop for Associative Array

Java - For-Each Loop for Associative Array, The for-each loop is specially used to handle elements of a collection or mostly i is used to handle associative array. A collection is represented by a group of elements or objects. List is an example of collection since it stores a group of objects.

The for-each loop is specially used to handle elements of a collection or mostly i is used to handling associative array.

A collection is represented by a group of elements or objects. List is an example of collection since it stores a group of objects.

 The for-each loop repeatedly execute a group of statements for each elements of the collection, but unfortunately you can't use for-each loop everywhere.

Java Source

public class ForEach {

 public static void main(String[] args) {
  int arr[]={1, 2, 3, 4, 5, 6,3,4,5,6,7};
  for(int i:arr){
   System.out.println(i/2F);
  }
 }

}

Output

0.5
1.0
1.5
2.0
2.5
3.0
1.5
2.0
2.5
3.0
3.5
In the above example, the class is ForEach, which has the main function. Inside the main function, the array is defined as integer data type. int arr[] = {1, 2, 3, 4, 5, 6, 3, 4, 5, 6, 7,}; and after that the for each loop is used, to use for-each loop you have to use variable name and collection i.e for(int i[Variable]:arr[Collection of array]){ statements; }. It will go repeatedly up the end of the element

Java Source

This program will help you to find out the even number from the collection of the list.

public class ForEach {

 public static void main(String[] args) {
  int arr[]={1, 2, 3, 4, 5, 6,3,4,5,6,7};
   for(int i:arr){
    if(i%2==0){
     System.out.println(i);
  }
 }
}
}

You May Also Like...