Arrays are used to store one type of data, whether it is a primitive or reference data type. Arrays themselves are reference types. They are best thought of as a list of items with a fixed size, as arrays have a set size that cannot be changed (don’t confuse this with ArrayLists which can also be thought of as a list - we'll learn about ArrayLists in Unit 6).
Arrays are denoted by braces ({}), with items separated by commas such as the following:
{true, true, false, true}
Before we can use arrays, we need to have an import statement, which is
import java.util.Arrays;
There are two ways to make arrays: using a constructor and using a pre-initialized array.
As with other reference types, we can initialize arrays using a constructor. However, the constructor is slightly different from the constructors from Unit 5:
dataType[] arrayName = new dataType[numberOfItems];
To create an array that holds 10 integers, we would do int[] ourArray = new int[10];
The items in the array are initialized differently depending on the data type.
Integers are initialized to 0
Doubles are initialized to 0.0
Booleans are initialized to false
All reference types are initialized to null
We will talk about filling constructed lists in the next topic when we discuss traversing arrays.
We can also set an array to a pre-initialized array, similar to how we initialize strings. Here, we will initialize an array of 10 integers as follows:
int[] arrayOne = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
We access elements in arrays using bracket notation as follows: arrayName[index]
. The most important thing to know is that Java is a zero-indexed language, so the first item has index 0, and not 1.
Before we talk about the index of the last item, we need to discuss how to find the array length. The array length is actually an instance variable specific to that particular array denoted as arrayName.length
(not to be confused with length() for Strings). Note that this is not a method, so there are no parentheses.
Thus, the last item in the array can be accessed by using arrayName.length - 1
. Do not confuse this with the constructor in which we use arrayName.length
in brackets.
If we use an index outside the allowed range, we will get an ArrayIndexOutOfBoundsException
.
Here is a question: how do we access the even numbers in arrayOne from above?
Answers
2 = arrayOne[1]
4 = arrayOne[3]
6 = arrayOne[5]
8 = arrayOne[7]
10 = arrayOne[9]