Monday 29 August 2016

Java for each

4.  for each loop
  • for each loop is used to apply  on only on arrays and collection objects to get the elements one by one from arrays/collection object.
  • By using for loop also we can get the elements one by one, but we might be feel for loop code is the complex.
  • Note : there is no each keyword in java
Syntax:

        for(variable : array/collection)
        {
           statements
        }
--------------------------------------------------------------------------------
Program         :     A program to print one by one elements from an array
Program name  :     ForEachDemo1.java
Output            : 
                            1
                            2
                            3
                            4
                            5  

class ForEachDemo1
{
       public static void main(String args[])
       {
                int i[] = {1,2,3,4,5};
  
                for(int j : i)
                {
                    System.out.println(j);
                }
       }
}

Compile     :           javac ForEachDemo1.java
Run           :           java ForEachDemo1
Output       : 
                            1
                            2
                            3
                            4
                            5         
  --------------------------------------------------------------------------------
Program         :     A program to print one by one elements from collection
Program name  :     ForEachDemo2.java
Output            : 
                            A 
                            B
                            C

import java.util.*;
class ForEachDemo2
{
       public static void main(String args[])
       {
                int i[] = {1,2,3,4,5};
  
          List list = new ArrayList();
          list.add("A");
          list.add("B");
          list.add("C");

          for(Object o : list)
          {
             System.out.println (o);
          }
       }
}

Compile     :           javac ForEachDemo2.java
Run           :           java ForEachDemo2
Output       : 
                            A 
                            B
                            C
  --------------------------------------------------------------------------------

Thanks for your time.
- Nireekshan