Lesson 9: Arrays — Traversals, Algorithms and the Enhanced for Loop
An array is a fixed-size collection of values of the same type, stored in order and reached by index, starting at 0. Declaring int[] scores = new int[5]; creates an array of five ints, all initially 0, and scores[2] refers to the third element. Arrays are the first data structure in the course, and they are everywhere in the free-response section: a list of grades, a row of pixels, a set of measurements. The fixed size is both their strength and their limit — you always know how much space an array takes, but you cannot grow it, which is why ArrayList exists and why the next lessons cover it.
Working with an array means traversing it: visiting each element in turn, usually with a for loop from index 0 to array.length − 1. The length is a public field, not a method, so you write scores.length with no parentheses, and the last valid index is scores.length − 1. Going beyond that throws an ArrayIndexOutOfBoundsException, the commonest array error, and it usually comes from using <= instead of < in the loop condition, or from starting at 1 instead of 0. When you write a traversal, check the first index, the last index, and the number of iterations, just as you did for plain loops.
The enhanced for loop, also called the for-each loop, is a shorter way to traverse an array when you only need each value and not its index: for (int score : scores) { ... } gives you each element in turn, with no index variable to get wrong. It is ideal for summing, finding a maximum, or printing every element. But it cannot change the array's elements in a useful way for primitives — assigning to the loop variable changes only the copy — and it cannot tell you where an element sits, so any algorithm that needs positions must use an ordinary indexed loop. Knowing which loop to choose is part of the skill.
The standard array algorithms are worth learning as patterns: summing all elements, finding the maximum or minimum, counting elements that satisfy a condition, and searching for a value. Each follows the same shape — initialize a result variable, traverse the array, update the result when the current element qualifies — and each appears in free-response questions in many disguises. A maximum search, for example, starts with the first element as the current maximum and replaces it whenever a larger value is found; starting with 0 instead would fail for an array of negative numbers. Write these patterns from scratch until they are automatic.
Arrays of objects behave differently from arrays of primitives in one important way: their elements start as null, not as zero. An array declared as String[] names = new String[5]; holds five null references until you assign a String to each slot, and calling a method on an element before assigning it causes a NullPointerException. Arrays can also be created with an initializer list, as in int[] primes = {2, 3, 5, 7, 11};, which builds the array and fills it in one step. The length of such an array is fixed by the list, and it cannot grow later. When you write a method that takes an array, remember that the method receives a reference to the caller's array, so changing an element inside the method changes the caller's array too.
A worked example
Worked example: the code below finds the largest value in an array and counts how many values exceed 80. Notice that the maximum starts as the first element, not as 0, and that the loop bounds use scores.length.
int[] scores = {72, 85, 91, 68, 88};
int max = scores[0];
int countAbove80 = 0;
for (int i = 0; i < scores.length; i++)
{
if (scores[i] > max)
{
max = scores[i];
}
if (scores[i] > 80)
{
countAbove80++;
}
}
System.out.println(max); // 91
System.out.println(countAbove80); // 3
The loop visits indices 0 to 4, updating max to 85, then 91, and counting 85, 91, and 88 as above 80. If the array had been empty, scores[0] would have thrown an exception, so a careful method checks for that case first. In free-response answers, always use array.length for the bound rather than a hard-coded number, because a hard-coded bound breaks if the array's size changes, and the marker will notice.
Key Terms
- Array
- A fixed-size, ordered collection of values of the same type, accessed by index from 0.
- Index
- The position of an element in an array, starting at 0.
- Traversal
- Visiting each element of an array in turn, usually with a loop.
- Enhanced for loop
- A for-each loop that visits each element's value without an index variable.
- ArrayIndexOutOfBoundsException
- The error thrown when an array is accessed with an index outside 0 to length − 1.
Discussion Questions
- Why is an array's size fixed, and when is that a problem?
- When would you use an enhanced for loop, and when must you use an indexed loop?
- Why should a maximum search start with the first element rather than 0?
Practice Questions
- int[] a = new int[4]; What are the valid indices, and what are the initial values?
- What is the last valid index of an array named data?
- Write an enhanced for loop that prints every element of int[] nums.
- What error occurs when you access a[5] in an array of length 5?
- Why can't an enhanced for loop change the elements of an int array?
Show answers
- Indices 0 to 3; all elements start at 0.
- data.length − 1.
- for (int n : nums) { System.out.println(n); }
- ArrayIndexOutOfBoundsException, because the valid indices are 0 to 4.
- Its loop variable holds a copy of each element's value, so assigning to it does not change the array.