EnhancedForLoopDemo.java.html

  1  public class EnhancedForLoopDemo
  2  {
  3     public static void main(String[] args)
  4     {
  5        int[] values = new int[10];
  6  
  7        // In this loop, we need the index value, so we can't use
  8        // an enhanced for loop.
  9  
 10        for (int i = 0; i < values.length; i++)
 11        {
 12           values[i] = i * i;
 13        }
 14  
 15        // In this loop, we don't need the index value. 
 16        // The enhanced for loop simplifies the code.
 17  
 18        int total = 0;
 19        for (int element : values)
 20        {
 21           System.out.println(element);
 22           total = total + element;
 23        }
 24  
 25        System.out.println("Sum: " + total);
 26     }
 27  }