For-each loop (Advanced or Enhanced For loop):

For-each loop (Advanced or Enhanced For 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.

Advantage of for-each loop:

  • It makes the code more readable.
  • It elimnates the possibility of programming errors.

Syntax of for-each loop:

  1. for(data_type variable : array | collection){}

Simple Example of for-each loop for traversing the array elements:

  1. class ForEachExample1{
  2.   public static void main(String args[]){
  3.    int arr[]={12,13,14,44};
  4.    for(int i:arr){
  5.      System.out.println(i);
  6.    }
  7.  }
  8. }

Test it Now

Output:12
       13
       14
       44

Simple Example of for-each loop for traversing the collection elements:

  1. import java.util.*;
  2. class ForEachExample2{
  3.   public static void main(String args[]){
  4.    ArrayList<String> list=new ArrayList<String>();
  5.    list.add(“vimal”);
  6.    list.add(“sonoo”);
  7.    list.add(“ratan”);
  8.    for(String s:list){
  9.      System.out.println(s);
  10.    }
  11.  }
  12. }

Test it Now

Output:vimal
       sonoo
       ratan
download this example
Next TopicVarargs
java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

For-each loop (Advanced or Enhanced For 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. Advantage of for-each loop: It makes the code more readable. It elimnates the […]

Tags:

....
...