... the counting details are hidden from you in the enhanced for statement:

for (int counter = 0; counter < array.length; counter++) {
   total += array[counter];
}

Fig. 7.12

 1   // Fig. 7.12: EnhancedForTest.java
 2   // Using the enhanced for statement to total integers in an array.
 3
 4   public class EnhancedForTest {
 5      public static void main(String[] args) {
 6         int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
 7         int total = 0;
 8
 9         // add each element's value to total
10         for (int number : array) {
11            total += number;
12         }
13
14         System.out.printf("Total of array elements: %d%n", total);
15      }
16   }
Total of array elements: 849

Using the enhanced for statement to total integers in an array.

The enhanced for statement can be used only to obtain array elements—it ...

Get Java How to Program, Early Objects, 11th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.