<< Hide Menu

📚

 > 

💻 

 > 

⌚️

6.3 Enhanced For Loop For Arrays

3 min readjune 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Now, we will introduce a special kind of for loop called the enhanced for loop. The enhanced for loop can be used to traverse through most data structures. Note that the enhanced for loop can only be used to traverse in the forward direction. To use it, we use this structure:

Structure for Enhanced 'For Loops'

for (dataType i: arrayName) {
  do something with i
}

This basically says that for every element i in the array, we do something to i

Limitations of Enhanced 'For Loops'

We can only access i, but we cannot change or set new values to i. Thus, we cannot do this:

/** Doubles each element of the array
*/
public static void doubleArray(int[] array) {
  for (int i: array) {
    i *= 2; // doubles each individual element
  }
}

Why? Remember that Java is a pass-by-value programming language. The variable i is only a copy of the actual element in the array and changing i only changes the copy, not the actual element itself. If you want to actually change the array elements, use regular for loops as in Topic 6.2.

However, we can use mutator methods on objects on the array to set the value of their instance variables. This is because i is a copy of the object reference, which means that i refers to the same object as the array element, so calling methods on i is the same as calling methods on the individual array elements themselves. 

Example

Here is an example of how we can use an enhanced for loop and mutator methods to set the value of an object's instance variables:

/** Represents a student
*/
public class Student {
  private String name;
  
  /** Sets the name of the Student
  */
  public void setName(String name) {
    this.name = name;
  }

  /** Other instance variables, methods, and constructors not shown
  */
}
// IN ANOTHER CLASS
/** Resets all students' names
*/
public static void doubleArray(Student[] array, String defaultName) {
  for (Student student: array) {
    student.setName(defaultName); // Sets each student's name to a default name
  }
}

It's important to note that enhanced for loops force us to traverse through the entire data structure. We can't just go to every other element or every third element because we have no control over what indices of the array the loop uses. 

Thus, while any enhanced for loop can be rewritten as a for loop or a while loop, there are for loop or while loop traversals that you cannot write as enhanced for loops. 

Let's see how we could write the enhanced for loop above as a for loop:

// IN ANOTHER CLASS
/** Resets all students' names
*/
public static void doubleArray(Student[] array, String defaultName) {
  for (int i = 0; i < array.length; i++) {
    array[i].setName(defaultName); // Sets each student's name to a default name
  }
}