Unit 4 · 20 min

4.4 Array Traversals

To change what is stored in an array, you need the index; the enhanced for loop only lends you copies.

Summary, objectives and course and exam description (CED) codes

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.

By the end of this session you can

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

4.4.A4.4.A.14.4.A.24.4.A.34.4.A.44.4.A.54.4.A.6

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

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

Lock it in: memory hooks

  • Enhanced for loopRead it as "for each": for each int s in scores. You get each value, never its address.
  • Copy ruleA copy in your hand is not the box on the shelf: change the copy, the shelf stays the same.
  • Objects in an enhanced for loopSame remote, same TV: the copy of a reference still controls the same object, so its methods can change it.

Common misconceptions

  • "In for (int s : scores), changing s changes the array."

    Not quite. 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.

  • "An enhanced for loop can never change anything."

    Not quite. 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.

  • "for (int i = 0; i <= arr.length; i++) visits every element."

    Not quite. With <= the last pass uses index arr.length, which is out of bounds. Use i < arr.length.

  • "A traversal always visits every element from first to last."

    Not quite. A traversal can visit an ordered sequence of elements: backward, every other element, or only part of the array. Indexed loops make that possible.

Exam traps

  • for (int i = 0; i <= arr.length; i++) throws an ArrayIndexOutOfBoundsException on its last pass.
  • Assigning to the enhanced for loop variable compiles and runs but changes nothing in the array.
  • A while loop that forgets i++ never ends (infinite loop).
  • Going backward starts at arr.length - 1, not arr.length, and stops after index 0 (i >= 0).

2PracticeRecall it, then check yourself

In 30 seconds

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

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Array Traversals

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 4.4.A.3, 4.4.A.4
    int[] pts = {3, 5, 7};
    for (int p : pts)
    {
        p = p * 2;
    }
    for (int p : pts)
    {
        System.out.print(p + " ");
    }
    Show answer

    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.

  2. 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? 4.4.A.2
    int[] v = {4, 9, 1};
    for (int i = v.length; i > 0; i--)
    {
        System.out.print(v[i] + " ");
    }
    Show answer

    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.

  3. 3 Consider the following class and code segment. What is printed as a result of executing the code segment? 4.4.A.5
    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());
    Show answer

    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.

  4. 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? 4.4.A.6
    for (String w : words)
    {
        System.out.print(w.substring(0, 1));
    }
    Show answer

    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.

  5. 5 Consider the following code segment. What is printed as a result of executing the code segment? 4.4.A.1, 4.4.A.2
    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);
    Show answer

    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).

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Traversaltap to flip

    Using repetition (or recursion) to access all elements of an array or ArrayList, or an ordered sequence of them.

    Example and CED codes
  • Enhanced for looptap to flip

    A loop that assigns a copy of each element of an array or ArrayList, in order, to its loop variable, without using an index.

    Example and CED codes
  • Arraytap to flip

    An object that stores a fixed number of values of the same type, either primitive values or object references, reached by an index.

    Example and CED codes
  • Elementtap to flip

    One value stored in an array or an ArrayList, at a position given by its index.

    Example and CED codes
  • Indextap to flip

    The position of a character in a String, counted from 0. Valid indices run from 0 to length() - 1.

    Example and CED codes
  • for looptap to flip

    An iterative statement whose header has three parts: the initialization (runs once), the Boolean expression (checked before each iteration) and the update (after each iteration).

    Example and CED codes
  • while looptap to flip

    An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.

    Example and CED codes
  • ArrayIndexOutOfBoundsExceptiontap to flip

    The run-time exception thrown when code uses an array index less than 0 or greater than or equal to the array's length.

    Example and CED codes

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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure