Please enable JavaScript to use CodeHS

Chapter 6

Arrays

6.1 Array

An array is a list of data. Arrays can store many different types of information. For example, if you had a shopping list, you could store the shopping list as an array.

Organizing Information in an Array

The information stored in an array is kept in order. The items in an array are often referred to as members or elements of the array. What makes arrays unique is that they store a fixed number of elements. Once an array is created, the size of the array cannot be changed.

It is important to note that in computer science, we usually start counting from 0. So the first item in the array is actually at index position 0, the second item in the array is at index position 1, and so on.

Let’s say our grocery list contained these items, in this order: apples, dog food, donuts, celery, and orange juice. If we were to draw out the array, it would look something like this:

index position: 0 1 2 3 4
list item: apples dog food donuts celery orange juice

We can see that dog food is at index 1 and celery is at index 3.

Creating Arrays

To create an array in Java, you must first know what type of data you want to store and how many elements the array will hold. In the grocery list example above, we created an array of Strings, but it’s just as easy to create arrays of integers or any other data type. Arrays can store both primitive and object data types.

The format for creating an array is:

type[] arrayName = new type[numberOfElements];
Plain text

Let’s take apart the array declaration:

  • type[]: This tells us what type of data is being stored in the array. For example, a list of integers would be int[]. The brackets [] indicate that this is an array and not a single int.
  • arrayName: The name by which the array will be known. It’s best to pick a descriptive name, like groceryList instead of just things.
  • new: The new keyword indicates that a new array is being created.
  • type[numberOfElements]: The type of elements is mentioned again, as well as the number of items the array will store. For example, if an array int[6] were created, the array would store six int values. Once an array has been created, the number of items that can be stored in the array cannot change. This array will always store 6 items - no more, no less!

For example, if you wanted to create an array that contained 6 integers, the initialization of the array would look like this:

// Create an empty array that will store 6 integers
int[] newNumberList = new int[6];
Plain text

When an array is initially created, each index in the array is set to a default value. Java assigns a specific value for each item in the array depending on the type. int and doubles default to zero, booleans default to false, and objects (including strings) default to null.

Type Default Value
int 0
double 0.0
boolean false
Objects null

Arrays can also be created and initialized with specific values. To do so, simply include the elements that will be stored in the array between curly braces in the initialization. Here’s a list of 6 numbers:

int[] numberList = {10,20,30,40,50,60};
Plain text

Setting Elements

Elements in an array can be accessed using the index position of the array. Let’s create a new empty array of numbers, then add in two numbers:

// Create an empty array that will store 6 integers
int[] newNumberList = new int[6];

// Add the number 11 to index position 0
newNumberList[0] = 11;

// Add the number 13 to index position 1
newNumberList[1] = 13;
Plain text

The array now contains two integers:

Index Position: 0 1 2 3 4 5
Array Item: 11 13 0 0 0 0

Notice that the rest of the indices in the array are set to the default value 0. The [] syntax can also be used to change elements in a list. Let’s change 13 to 21:

newNumberList[1] = 21;
Plain text
Index Position: 0 1 2 3 4 5
Array Item: 11 21 0 0 0 0

Getting Elements

Accessing an element in a list uses a similar syntax. We can get and store the number at index 0 into a variable:

// This variable will contain the number 11
int firstNumber = newNumberList[0];

// Two ways to print out the number 11 to the console
System.out.println(firstNumber);
System.out.println(newNumberList[0]);

// Now print out the number at index position 1 to the console
System.out.println(newNumberList[1]);
Plain text

The output from the code will be:

11
11
21
Plain text

ArrayIndexOutOfBoundsError

Accessing a value in an array that’s outside the current index value list will result in an ArrayIndexOutOfBoundsException. For example, a new double array is created with 5 values:

double[] example = new double[5];
Plain text

Because there are only five values in this array, attempting to access an index greater than or equal to five will throw an error:

double value = example[6];   //This results in an ArrayIndexOutOfBoundsException
Plain text

This program would throw an ArrayIndexOutOfBoundsException, as index six is unavailable in this particular array. If you see this error in a program, it most likely means that you’re accessing an array incorrectly!

Making an Array

Make an Empty Array

Indexing Into an Array

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    How do you initialize an array called arr of 10 double with default values?

Exercise: Our First Array

Let’s make our first arrays!

Create 3 arrays as described below:

  • A String array to hold the names of the following cities: San Juan, Accra, and Sao Paulo

  • An int array that holds the population of each city:
    -San Juan: 335,468
    -Accra: 2,557,000
    -Sao Paulo: 12,330,000

  • A double array that holds the average minimum amount of sunshine the city gets:
    -San Juan: 7.5 hrs/day
    -Accra: 6.5 hrs/day
    -Sao Paulo: 6.05 hrs/day

Make sure you keep the array elements in the same order so that the same index can be used to get corresponding cities, population, and hours of sunshine. These are called parallel arrays.

Then print out the information for each city. Your output should look like the example below.

OUTPUT:

San Juan's population is 335468.
Accra's population is 2557000.
Sao Paulo's population is 12330000.

The least amount of sunshine San Juan gets is 7.5 hours a day.
The least amount of sunshine Accra gets is 6.5 hours a day.
The least amount of sunshine Sao Paulo gets is 6.05 hours a day.
Plain text