Java Tutorial : For-Each Loop




This loop is specially  designed for collection elements. Collection means a group of elements. For example , we can take an array as a collection or any class in java.util package can be considered as a collection. The reason is that an array stores a group of elements like integer values or strings.


Syntax:

for(val : collection)
  {
      statements;
  }



Here , the var is attached to the collections.This var represents each element of the collection one by one.

Example : here is a program to see the use of for-each loop and retrieve the elements one by one from an array and display it.

// using for each loop to display array elements
class demo {

  public static void main(String[] args) {
    //Declare an array with 4 elements

    int arr[] = { 210, 540, 230, -23 };

    // Use of  for-each Loop

    for (int i : arr) {
      System.out.println(i);
    }
  }
}

No comments

Powered by Blogger.