Enhanced for Statement

One Dimensional Arrays

Enhanced for Statement

🙋 Need help? Ask an expert now!

Let's examine another type of loop. The "enhanced for" statement, or the "for-each" loop, looks at each element of an array in order, which allows the loop to automatically avoids errors such as going past the last index of an array. Let's revisit the same goal as in the example on previous page, but try it now with the for-each loop.

package exlcode;

public class EnhancedForLoopExample {

  public static int[] exampleVariableOne = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  public static int sum = 0;
  public static void main(String[] args) {
    // simplifies the for loop and creates simple code
    // 1D array
    for (int count : exampleVariableOne) {
      sum += exampleVariableOne[count];

The syntax for an "enhanced for statement" is as follows, for(datatype variablename : arrayname). The "datatype" and "variablename" is what you would put in the first section of a for loop, the loop control variable. This creates a new variable that only exists within the "for-each" loop. It is used as the index when accessing the elements of the array.

The "for-each" loop is used when you want to loop through each and every element of the array without missing out an index or accidentally exceeding the last index of the array. When you code a program that only accesses certain elements inside an array, you can still use the "for-each" loop. However, as it requires an extra if statement to do so, you may choose to use a regular for loop with incrementing/decrementing variables as shown in past topics.

Edit Me on GitHub!

Application Question