Fiveable
Fiveable
crams
AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

6.3 Enhanced For Loop For Arrays

Verified for the 2025 AP Computer Science A examCitation:

The enhanced for loop (also called the "for-each" loop) provides a simpler, cleaner way to traverse arrays when you only need to access each element's value. This handy shortcut helps you write more readable code while avoiding common index-related errors.

What is the Enhanced for Loop?

The enhanced for loop is a special loop designed specifically for going through collections of items like arrays. It automatically handles the details of stepping through each element, making your code cleaner and less prone to errors.

Basic Syntax

for (DataType variableName : arrayName) {
    // Code to process each element
}

Where:

  • DataType is the type of elements in the array
  • variableName is a new variable that will hold each element
  • arrayName is the array you want to traverse

How the Enhanced for Loop Works

Behind the scenes, the enhanced for loop:

  1. Starts at the beginning of the array
  2. Creates a temporary variable to hold a copy of the current element
  3. Executes the loop body using that variable
  4. Moves to the next element
  5. Repeats until it reaches the end of the array

Example: Printing Array Elements

int[] scores = {95, 87, 72, 93, 84};

// Using enhanced for loop
for (int score : scores) {
    System.out.println(score);
}

This code prints each score on a separate line, without needing to track any index variables.

Important Limitations

1. The Loop Variable Contains a Copy

An essential concept to understand: the variable in the enhanced for loop header contains a copy of the element, not a direct reference to the element in the array.

int[] numbers = {1, 2, 3, 4, 5};

// Trying to modify array elements (DOESN'T WORK)
for (int num : numbers) {
    num = num * 2;  // This only modifies the copy, not the array element!
}

// The array remains unchanged
for (int num : numbers) {
    System.out.print(num + " ");  // Still prints: 1 2 3 4 5
}

2. Cannot Modify the Array Structure

The enhanced for loop doesn't give you access to the element's position (index), so you can't:

  • Insert or remove elements
  • Modify elements at specific positions
  • Know which position you're currently processing

When to Use the Enhanced for Loop

The enhanced for loop is best used when you:

  • Need to process every element in the array
  • Don't need to know the index/position of elements
  • Don't need to modify the array elements

Comparing Loop Styles

Here's the same task done with both types of loops:

Task: Calculate the sum of all elements in an array

Using an indexed for loop:

int[] values = {10, 20, 30, 40, 50};
int sum = 0;

for (int i = 0; i < values.length; i++) {
    sum += values[i];
}

System.out.println("Sum: " + sum);  // 150

Using an enhanced for loop:

int[] values = {10, 20, 30, 40, 50};
int sum = 0;

for (int value : values) {
    sum += value;
}

System.out.println("Sum: " + sum);  // 150

Notice how the enhanced version is shorter and focuses on what we're doing with each value.

Converting Between Loop Types

Any enhanced for loop can be rewritten as a standard indexed for loop:

// Enhanced for loop
for (String name : names) {
    System.out.println(name);
}

// Equivalent indexed for loop
for (int i = 0; i < names.length; i++) {
    String name = names[i];
    System.out.println(name);
}

However, not all indexed for loops can be converted to enhanced for loops, especially when:

  • You need to know the index
  • You need to modify the array elements
  • You're not processing every element

Common Use Cases for Enhanced for Loop

Searching for a Value

String[] fruits = {"Apple", "Banana", "Orange", "Mango", "Kiwi"};
String searchFor = "Mango";
boolean found = false;

for (String fruit : fruits) {
    if (fruit.equals(searchFor)) {
        found = true;
        break;
    }
}

System.out.println(found ? "Found it!" : "Not found!");

Counting Elements That Meet a Condition

int[] scores = {76, 89, 95, 68, 90, 83, 92, 71};
int count = 0;

for (int score : scores) {
    if (score >= 90) {
        count++;
    }
}

System.out.println(count + " students scored an A");  // 3 students scored an A

Processing Objects in an Array

Student[] students = {new Student("Alice"), new Student("Bob"), new Student("Charlie")};

for (Student student : students) {
    student.graduate();  // This modifies the object, not the array reference
}

Enhanced for Loop with Different Array Types

The enhanced for loop works with arrays of any type:

Primitive Type Arrays

double[] prices = {19.99, 9.99, 15.99, 24.99};

for (double price : prices) {
    System.out.printf("$%.2f\n", price);
}

Object Arrays

String[] names = {"Alice", "Bob", "Charlie"};

for (String name : names) {
    System.out.println("Hello, " + name + "!");
}

Summary

The enhanced for loop provides a cleaner, simpler way to traverse arrays when you only need to access each element's value. It automatically handles the details of stepping through each element, making your code more readable. Remember that the loop variable contains a copy of each element, so you cannot use it to modify the array contents. While the enhanced for loop has limitations (no index access, can't modify array elements), it's an excellent choice for many common array operations where you simply need to process each value.

Key Terms to Review (4)

Enhanced For Loop: An enhanced for loop (also known as a foreach loop) is a simplified way to iterate over elements in an array or collection. It automatically handles indexing and provides an easy way to access each element without explicitly using indices.
Mutator Methods: Mutator methods are special types of methods in object-oriented programming that allow modification or mutation of an object's attributes or properties.
Pass-by-value: Pass-by-value is the method of passing arguments to functions or methods by creating copies of their values instead of directly passing references to them.
Traverse: Traversing refers to the process of accessing each element in a data structure (such as arrays or linked lists) one by one, usually for performing some operation on them.