# AP® Computer Science A 4.4 Array Traversals

Source: https://lockincs.com/ap-csa/unit-4/4-4-array-traversals/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 4.4.A, 4.4.A.1, 4.4.A.2, 4.4.A.3, 4.4.A.4, 4.4.A.5, 4.4.A.6

Traversing an array means using repetition statements to access all of its elements or an ordered sequence of them. Indexed for loops and while loops reach elements through their indexes, so they can change the array. An enhanced for loop gives its variable a copy of each element without an index, so assigning to that variable never changes the array, although calling methods on an object element can change that object's attributes.

## What you will learn

- 4.4.A Develop code used to traverse the elements in a one-dimensional (1D) array and determine the result of these traversals.

## 1\. What a traversal is

Traversing an array means using repetition statements (loops) to access all of the elements in an array, or an ordered sequence of them 4.4.A.1. “Ordered sequence” matters: a traversal can visit every element front to back, but also backward, every other element, or just part of the array.

## 2\. Indexed for loops and while loops

A traversal with an indexed `for` loop or a `while` loop accesses the elements through their indexes 4.4.A.2. The loop variable is the index, and `arr[i]` is the element.

```
int[] temps = {12, 15, 9, 20};

for (int i = 0; i < temps.length; i++)
{
    System.out.println("Day " + i + ": " + temps[i]);
}
```

Output:

```
Day 0: 12
Day 1: 15
Day 2: 9
Day 3: 20
```

The same traversal written as a `while` loop: the three parts of the `for` header move to three places 4.4.A.2.

```
int[] temps = {12, 15, 9, 20};

int i = 0;                      // start
while (i < temps.length)        // condition
{
    System.out.println("Day " + i + ": " + temps[i]);
    i++;                        // update
}
```

Output:

```
Day 0: 12
Day 1: 15
Day 2: 9
Day 3: 20
```

Because you control the index, you can visit an ordered sequence instead of everything:

```
int[] temps = {12, 15, 9, 20, 17};

for (int i = temps.length - 1; i >= 0; i--)     // backward
{
    System.out.print(temps[i] + " ");
}
System.out.println();

for (int i = 0; i < temps.length; i += 2)       // every other element
{
    System.out.print(temps[i] + " ");
}
System.out.println();
```

Output:

```
17 20 9 15 12 
12 9 17 
```

An indexed loop can also **change** elements, because `temps[i]` on the left of `=` writes into the array:

```
int[] temps = {12, 15, 9, 20};
for (int i = 0; i < temps.length; i++)
{
    temps[i] = temps[i] * 2;
}
System.out.println(temps[0] + " " + temps[1] + " " + temps[2] + " " + temps[3]);
```

Output:

```
24 30 18 40
```

**Watch out:** the most common traversal bug is `<=` instead of `<`.

```
int[] temps = {12, 15, 9, 20};
for (int i = 0; i <= temps.length; i++)
{
    System.out.println(temps[i]);
}
```

Output:

```
12
15
9
20
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
```

## 3\. The enhanced for loop

An enhanced `for` loop header declares a variable, called the enhanced for loop variable. On each iteration, that variable is assigned a copy of the next element, without using its index 4.4.A.3. Read the colon as “in”: “for each `score` in `scores`”.

```
int[] scores = {8, 6, 10};
int total = 0;

for (int score : scores)
{
    total += score;
}
System.out.println("Total: " + total);
```

Output:

```
Total: 24
```

The type of the loop variable must match the element type (`int` for an `int[]`, `String` for a `String[]`).

## 4\. Assigning to the loop variable changes nothing

Because the loop variable holds a copy, assigning a new value to it does not change the value stored in the array 4.4.A.4.

```
int[] scores = {8, 6, 10};

for (int score : scores)
{
    score = 0;                  // changes only the copy
}
System.out.println(scores[0] + " " + scores[1] + " " + scores[2]);
```

Output:

```
8 6 10
```

| index | 0 | 1 | 2 |
| --- | --- | --- | --- |
| `scores` before | 8 | 6 | 10 |
| `scores` after | 8 | 6 | 10 |

The code compiles and runs with no error, which is why this is a classic exam trap. To reset the array, use an indexed loop: `scores[i] = 0;`.

## 5\. Enhanced for loops with object references

When an array stores object references, the loop variable gets a copy of each **reference**. The copy still points to the same object, so calling a method on the loop variable can modify that object’s attributes 4.4.A.5. What it does not change is the references stored in the array 4.4.A.5.

```
public class Team
{
    public static void main(String[] args)
    {
        Player[] squad = {new Player("Mia", 3), new Player("Sam", 5)};

        for (Player p : squad)
        {
            p.addPoints(10);            // changes the object p refers to
        }
        System.out.println(squad[0].getPoints() + " " + squad[1].getPoints());

        for (Player p : squad)
        {
            p = new Player("New", 0);   // changes only the copy of the reference
        }
        System.out.println(squad[0].getName() + " " + squad[1].getName());
    }
}

class Player
{
    private String name;
    private int points;

    public Player(String n, int pts)
    {
        name = n;
        points = pts;
    }

    public void addPoints(int amount)
    {
        points += amount;
    }

    public int getPoints()
    {
        return points;
    }

    public String getName()
    {
        return name;
    }
}
```

Output:

```
13 15
Mia Sam
```

The first loop changed the players’ points (an attribute of each object). The second loop tried to put new players in the array, but the array still refers to Mia and Sam.

## 6\. Rewriting an enhanced for loop

Code that traverses an array with an enhanced `for` loop can always be rewritten with an indexed `for` loop or a `while` loop 4.4.A.6. The pattern: the loop variable `x` becomes `arr[i]`.

```
String[] words = {"red", "blue", "green"};

for (String w : words)                        // enhanced for
{
    System.out.print(w.length() + " ");
}
System.out.println();

for (int i = 0; i < words.length; i++)        // indexed for
{
    System.out.print(words[i].length() + " ");
}
System.out.println();

int k = 0;                                    // while
while (k < words.length)
{
    System.out.print(words[k].length() + " ");
    k++;
}
System.out.println();
```

Output:

```
3 4 5 
3 4 5 
3 4 5 
```

The opposite is not always possible. Choose an indexed loop when you need any of these:

| You need to… | Enhanced for? | Indexed for or while? |
| --- | --- | --- |
| read every element, in order | yes | yes |
| know the position (index) of an element | no | yes |
| compare an element with its neighbor | no | yes |
| change the values stored in the array | no | yes |
| go backward or skip elements | no | yes |

## Common mix-ups

- Not true: In for (int s : scores), changing s changes the array. s holds a copy of the element. Assigning a new value to s does not change the value stored in the array. Use an indexed loop and scores[i] = ... to change elements.
- Not true: An enhanced for loop can never change anything. If the array stores object references, calling a mutator method on the loop variable changes that object's attributes. It still cannot replace which objects the array refers to.
- Not true: for (int i = 0; i <= arr.length; i++) visits every element. With <= the last pass uses index arr.length, which is out of bounds. Use i < arr.length.
- Not true: A traversal always visits every element from first to last. A traversal can visit an ordered sequence of elements: backward, every other element, or only part of the array. Indexed loops make that possible.

## In 30 seconds

- Traversing an array uses repetition statements to access all or an ordered sequence of its elements.
- Indexed for loops and while loops access elements by their indexes: arr[i].
- An enhanced for loop variable gets a copy of each element, with no index.
- Assigning a new value to the enhanced for loop variable does not change the array.
- With object references, methods called on the loop variable can change the objects' attributes, but not the references stored in the array.
- Any enhanced for loop over an array can be rewritten as an indexed for loop or a while loop.

## Checkpoint: 5 practice questions

### Question 1

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int[] pts = {3, 5, 7};
for (int p : pts)
{
    p = p * 2;
}
for (int p : pts)
{
    System.out.print(p + " ");
}
```

- A. 6 10 14
- B. 3 5 7
- C. 0 0 0
- D. 3 10 14

**Answer: B.** The enhanced for loop variable `p` holds a copy of each element, so `p = p * 2` changes only the copy and the array still holds 3, 5 and 7. "6 10 14" assumes the array was changed, "0 0 0" confuses it with default values, and "3 10 14" assumes only some elements changed.

### Question 2

The following code segment is intended to print the elements of `v` from last to first. Which of the following best describes what happens when it is executed?

```java
int[] v = {4, 9, 1};
for (int i = v.length; i > 0; i--)
{
    System.out.print(v[i] + " ");
}
```

- A. 1 9 4 is printed
- B. 1 9 is printed and the loop ends
- C. An `ArrayIndexOutOfBoundsException` is thrown before anything is printed
- D. 9 1 is printed

**Answer: C.** The loop starts at `i = 3`, which equals `v.length`, so the first access `v[3]` is out of bounds and the exception is thrown before anything prints. The fix is to start at `v.length - 1` and continue while `i >= 0`. The other options assume the first index is valid.

### Question 3

Consider the following class and code segment. What is printed as a result of executing the code segment?

```java
public class Bulb
{
    private int watts;

    public Bulb(int w)
    {
        watts = w;
    }

    public void dim()
    {
        watts = watts / 2;
    }

    public int getWatts()
    {
        return watts;
    }
}

// code segment in another class
Bulb[] lamps = {new Bulb(60), new Bulb(40)};
for (Bulb b : lamps)
{
    b.dim();
    b = new Bulb(100);
}
System.out.println(lamps[0].getWatts() + " " + lamps[1].getWatts());
```

- A. 30 20
- B. 100 100
- C. 60 40
- D. 50 50

**Answer: A.** The loop variable `b` gets a copy of each reference, so `b.dim()` halves the watts of the real objects (60 to 30, 40 to 20). Assigning `b = new Bulb(100)` changes only the copy, not the references stored in the array, so "100 100" is wrong. "60 40" ignores the method call, and "50 50" averages the values.

### Question 4

Consider the following code segment, where `words` is a `String` array with at least one element. Which of the following code segments produces the same output for every such array?

```java
for (String w : words)
{
    System.out.print(w.substring(0, 1));
}
```

- A. `for (int i = 1; i <= words.length; i++) { System.out.print(words[i].substring(0, 1)); }`
- B. `for (int i = 0; i < words.length; i++) { System.out.print(words.substring(0, 1)); }`
- C. `for (int i = 0; i < words.length; i++) { System.out.print(words[0].substring(0, 1)); }`
- D. `for (int i = 0; i < words.length; i++) { System.out.print(words[i].substring(0, 1)); }`

**Answer: D.** An enhanced for loop can be rewritten as an indexed loop where the loop variable `w` becomes `words[i]`, for `i` from 0 to `words.length - 1`. Starting at 1 and using `<=` skips the first word and then goes out of bounds; `words.substring` does not compile because an array has no `substring` method; and `words[0]` prints the first letter of the first word every time.

### Question 5

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int[] d = {2, 7, 1, 8, 2, 8};
int sum = 0;
int i = 1;
while (i < d.length)
{
    sum += d[i];
    i += 2;
}
System.out.println(sum);
```

- A. 5
- B. 23
- C. 28
- D. 15

**Answer: B.** The loop visits an ordered sequence: indexes 1, 3 and 5, so it adds 7 + 8 + 8 = 23. "5" adds the even indexes (2 + 1 + 2), "28" adds every element, and "15" stops one element early (7 + 8).

## Questions students ask

**What is the difference between a for loop and an enhanced for loop in Java?**

An indexed for loop uses an index variable, so it can choose which elements to visit and can change them with arr[i] = value. An enhanced for loop gives you a copy of each element in order, with no index.

**Can an enhanced for loop modify an array?**

Not the values stored in it. Assigning to the loop variable only changes the copy. If the elements are object references, calling a mutator method on the loop variable does change those objects.

**How do I loop through an array backward?**

Use an indexed loop that starts at arr.length - 1 and goes down while i >= 0, for example for (int i = arr.length - 1; i >= 0; i--).

**When should I use an enhanced for loop?**

When you only need to read every element in order, such as to sum, count or search. If you need indexes, neighbors, a partial range or to change elements, use an indexed loop.

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
