8. 1000 - Arrays

Help Make These Materials Better!

I am actively working to complete and revise this eBook and the accompanying videos. Please consider using the following link to provide feedback and notify me of typos, mistakes, and suggestions for either the eBook or videos:

What’s the Point?

  • Understand the purpose of arrays

  • Create and use arrays

  • Write loops to iterate through arrays

Source code examples from this chapter and associated videos are available on GitHub.


8.1. Arrays and Indexes

The variables we’ve used to this point can only store one piece of data at a time, and sometimes we need to store more than that. For example, we might need to store a list of items to buy at the grocery store. I could create a variable for each item, but that would be a lot of variables to keep track of. Arrays give us a way to store multiple pieces of data in a single collection.

Each individual value in an array can be referred to as an element. Each element in an array has a unique index that tells us where it is in the array. The number of elements in an array is called the length of the array. The first element in an array has an index of 0, the second element has an index of 1, and so on. The last element in an array is always the length of the array minus one. If our grocery list has 5 items, the indexes of the items would be 0, 1, 2, 3, and 4.

Time to Watch!

Introduction to Arrays

8.2. Defining and Using Arrays

In Java, arrays are objects, so they have to be created with the new keyword, and array identifiers use square brackets [] to specify array elements.

Any time you see square brackets in Java, you’re dealing with an array.

The following example shows how an array is declared and initialized:

1
String[] groceryItems = new String[5];

This code creates an array of String objects called groceryItems that can hold 5 elements.

Once we have an array, we can assign values to its elements using the index, which is placed in square brackets after the array name:

1
2
3
4
5
groceryItems[0] = "milk";
groceryItems[1] = "eggs";
groceryItems[2] = "bread";
groceryItems[3] = "butter";
groceryItems[4] = "cheese";

Each element in the array is assigned a value, and the index is used to specify which element is being assigned.

Once we have values in an array, we can access them using the index. The element is just like any other variable, so we can use it in expressions, pass it to methods, and so on.

1
2
3
4
System.out.println("The first item on the list is " + groceryItems[0]);
System.out.println("The last item on the list is " + groceryItems[4]);
groceryItems[2] = "bananas";
System.out.println("Bread has been replaced with " + groceryItems[2]);

When using arrays, we have to be careful to stay within the bounds of the array. If we try to access an element that doesn’t exist, we’ll get an ArrayIndexOutOfBoundsException. This is a runtime exception, so it won’t be caught by the compiler, and it will cause our program to crash. In all arrays, any index less than 0 or greater than or equal to the length of the array is out of bounds. In our grocery list example, any index greater than 4 would be out of bounds.

Time to Watch!

Array Syntax in Java

Files from video:

8.3. Traversing Arrays

Working with individual elements in an array can be useful, but to really see the power of arrays, you need loops. With a loop, we can easily move through an array and perform some task or operation on each element. For example, if we have an array of quiz scores, we could use a loop to add up all the scores and calculate the average.

When we use a loop to go through an array, we are traversing the array. We can use a traversal to put values into an array (which we call populating the array), to modify values in an array, or to read values from an array. We can also use a traversal to search for something within an array.

Most of the time, we’ll use a simple for loop to traverse an array. The syntax for a for traversal is:

Example of a for loop to traverse an array
1
2
3
4
5
6
int scores[] = {90, 85, 95, 88, 92};
int sum = 0;
for (int i = 0; i < scores.length; i++) {
    sum += scores[i];
}
System.out.println("The sum of the scores is " + sum);

In this example, we have an array of quiz scores. We use a for loop to go through each element of the array and add it to the sum variable. Using a variable like sum to accumulate a value is a common pattern in programming, and we refer to such as variable as an accumulator. Notice that we declare and initialize it before the loop, and then we update it inside the loop. If we declare it inside the loop, it will be reset to zero each time the loop runs, and we won’t get the correct sum. It also wouldn’t be accessible outside of the loop due to its scope.

At this point, clever students point out that we could get the sum of the scores without using a loop at all, using the Arrays class from the java.util package. Sure, but since we’re learning about loops, that would defeat the point. My assignments for this chapter assess your ability to write loops, so you won’t get any points for code that doesn’t at least try to traverse the array.

In the example, notice that we use the length property of the array to set the loop condition. That way, this same loop will work for any array of any size. If we hard-coded the size of the array into the loop, we would have to change our code every time we changed the size of the array.

Example of a hard-coded loop
1
2
3
4
5
6
int scores[] = {90, 85, 95, 88, 92};
int sum = 0;
for (int i = 0; i < 5; i++) { // Uh oh! What if we add another score?
    sum += scores[i];
}
System.out.println("The sum of the scores is " + sum);
Time to Watch!

Loops and Arrays in Java

Files from video:

The Lab Assignments in Canvas can be completed using what we’ve covered to this point. You might choose to complete that work now, then move onto the rest of the chapter—​which you’ll need for the Programming Project.

8.4. Putting Objects in Arrays

In Java, an array can hold a primitive type, like an int, or an object. We’ve been using arrays of Strings, which are objects, but students sometimes don’t realize that they can also create arrays of objects they define themselves.

If we were to define a GroceryItem class with fields for the name and the aisle where it’s located, we could create an array of GroceryItem objects.

1
2
3
4
5
6
GroceryItem[] groceryItems = new GroceryItem[5];
groceryItems[0] = new GroceryItem("milk", 4);
groceryItems[1] = new GroceryItem("eggs", 9);
groceryItems[2] = new GroceryItem("bread", 7);
groceryItems[3] = new GroceryItem("butter", 4);
groceryItems[4] = new GroceryItem("cheese", 4);

Putting objects in an array expands the possibilities of what we can do with arrays. Our array can hold multiple objects, and each object can have multiple fields—​this allows arrays to manage large amounts of data in a single collection.

Time to Watch!

Putting Objects in Arrays

Files from video:

8.5. "For-Each" Loops

Because array traversal is such a common task, Java provides a special kind of loop that makes it easier to traverse an array. It is officially known as an enhanced for loop, but it is often called a "for-each loop" because it goes through each element in the array. A for-each loop is easy to write, and because it handles index management for us, it is less error-prone than a traditional for loop. However, it is less flexible than a traditional for loop: we can’t use it when we need to know the index of the element we’re working with, or when we need to move through the array in a different order.

The for-each loop is optional. You can always use a traditional for loop to traverse an array, and you’ll need to know how to do that for the assignments in this chapter.
Time to Watch!

"For-Each" Loops in Java

Files from video:


Check Yourself Before You Wreck Yourself (on the assignments)

Can you answer these questions?

  1. What is an array and how does it differ from a single variable?

  2. What is an ArrayIndexOutOfBoundsException and when does it occur?

  3. How can loops be used to traverse an array? Provide an example of a for loop that sums the elements of an integer array.

Sample answers provided in Stuff That’s Tacked On The End.