Skip Top Navigation Bar

Introduction to Arrays an AP Computer Science A Topic

Consider the following. You are tracking the scores in a bowling game. In bowling, there are ten rounds. Results from individual rounds must be preserved, since sometimes the results of one round influence the results of the next, like in the case of bowling a strike (knocking down all 10 pins in one roll) or a spare (knocking down all pins in two rolls).

To solve this, we could use a series of variables. Suppose Round is a class to hold the values in each round of the bowling game:

Round round1;
Round round2;
...
Round round10;

As an alternative, you could store these values in one data structure. There are several types of data structures, in this tutorial, we will explore using an array. An array is a type of data structure that has a fixed length. All the data stored in an array are of the same type.

How Data is Stored?

Each value stored in an array is called an element. The size of the array is set when it is declared and created. This size does not change. So if more elements are needed a new array would need to be created, the current elements copied over, and the new elements added. Alternatively, you can use another stucture, like an ArrayList.

Similar to the characters in a String, each element in an array has an index. The first index is 0 and the last is the size of the array - 1.

Constructing an Array

When constructing an array object, we must specify the type of data that is stored. An array can store either primitive or reference data.

General Format for Constructing an Array

<type of data>[] nameOfArray = new <type of data>[<number of elements>];

An example of an array of rounds for bowling using the Round class would be as follows:

Round[] bowlingCard = new Round[10];

Initial Values of an Array

When we create an array, some initial values are stored in the array.

Your Turn

Let's try it in the Java Playground.

Constructing an Array with Initial Values

We can also create an array and provide all the initial values. One way we can do this is by using an initializer list. This is good for when you have a shorter list of known values for an array. The values are listed in braces ({ }) and the array is assigned this list.

    <type of data> [] nameOfArray = {<values separated by a comma>};

Your Turn

Let's try it in the Java Playground.

Determine the Length of an Array

You can access the constant length to access the number of elements in an array.

int[] grades = {80, 70, 90, 95};
int numElements = grades.length;

Your Turn

Let's try it in the Java Playground.

Accessing Elements of an Array

To access the elements of an array, use square brackets ([ ]) and include the index value in the square brackets. If we want to access the first element of an array of grades, it would look like this:

int[] grades = {80, 70, 90, 95};
int firstGrade = grades[0];

Your Turn

Let's try it in the Java Playground.

Next Lesson

Resources