To keep track of 10 exam scores, we could declare 10 separate variables: int score1, score2, score3, … , score10; But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple data structure for a collection of related data that makes this easier. We’re going to explore data structures quite a bit this year. We’ll start by using Java’s data structures and we’ll quickly move into building and using our own.
A building block of many of the Collections (another name for a specific subset of data structures) is the Array. You can store a value in an array using an index (location in the array). An array index is like a locker number. It helps you find a particular place to store your stuff and retrieve stuff. You can get or store a value from or to an array using an index.
Three important things to note about Arrays:
Declaring Arrays
When we declare a variable, we specify its type and then the variable name. To make a variable into an array, we put square brackets after the data type. For example, int[] scores
means we have an array called scores that contains int values.
// Declaration for a single int variable int score; // Declaration for an array of ints int[] scores;
The declarations do not create the array. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn’t been created yet and you try to print the value of the variable, it will print null (meaning it doesn’t reference any object yet).
There are two ways to create an array. You can use the keyword new to get new memory:
//declare an array variable int[] highScores; // create the array highScores = new int[5]; // declare and create array in 1 step! String[] names = new String[5];
OR you can use use an initializer list to set up the values in the array:
int[ ] highScores = {99,98,98,88,68};
String[ ] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"};
Array elements are initialized to default values like the following if the keyword new is used for initialization.
int
double
boolean
String
Arrays know their length (how many elements they can store). It is a public read-only instance variable so you can use dot-notation to access the instance variable (arrayName.length
). Dot-notation is using variable name followed by a .
and then the instance variable (property) name or a method name.
int[ ] highScores = {99,98,98,88,68};
System.out.println(highScores.length);
To access the items in an array, we use an indexed array variable which is the array name and the index inside of square bracket [ ]. Remember that an index is a number that indicates the position of an item in a list, starting at 0.
// assign a new value 99 to the first element in the array
highScores[0] = 99;
// print the third element of the array
System.out.println( highScores[2] );