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.
Reviewed against the CED on
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
- 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.
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.
3PrevailLock it in for exam day
By the numbers
- Loops that can traverse an array three loops CED 4.4.A.2, 4.4.A.3
- indexed for loopuses indexes
- while loopuses indexes
- enhanced for loopuses copies, no index
- Limits of the enhanced for loop on an array four limits CED 4.4.A.3, 4.4.A.4, 4.4.A.5
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.