Introduction: 6.3.0

  • for each loop is an enhanced kind of for loop
    • It is easier to write
      • doesn’t involve an index variable
    • sets a variable to each value in the array successively
  • type of variable must be the type used in the array
  • Can also work with other collections like ArrayLists
int[] testScores = {33, 94, 87, 76};

for (int score : scores) {
    System.out.println(score);
}

For-each loop limitations: 6.3.1

  • You can’t modify array values using a for-each loop
  • You can’t use an index
  • You can’t iterate parts of an array, or do a different order

Summary: 6.3.4

  • A for-each loop can be used to loop through an array without using an index
  • Includes a variable; enhanced for loop variable
    • holds a copy of each value of the array
  • enhanced for loops can be rewritten to use regular for or while loops