6.1. Array Creation and Access

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. In App Inventor, this is called a list. In Java and many programming languages, this is called an array.

An array is a block of memory that stores a collection of data items of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you don’t need to name each one. Instead you use the array name and a number (called an index) for the position of an item in the array.

Here’s a fun video that introduces the concept of an array and gives an example.

An array is like a row of small lockers, except that you can’t cram lots of stuff into it. You can only store one value at each locker.

../_images/rowLockers.jpg

Figure 1: A row of lockers

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. Arrays and lists in most programming languages start counting elements from the number 0, so the first element in an array is at index 0. If you used App Inventor in the past, you might remember that list elements there start at 1 instead of 0, so make sure you remember that in Java, arrays start the index at 0!

6-1-1: Can you think of another example of something that is like an array (like a row of lockers)?

6.1.1. Declaring and Creating an Array

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. This data type will be for all the elements in the array.

// 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).

To actually create an array after declaring the variable, use the new keyword with the type and the size of the array (the number of elements it can hold). This will actually create the array in memory. You can do the declaration and the creation all in one step, see the String array names below. The size of an array is set at the time of creation and cannot be changed after that.

//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];

exercise Check Your Understanding

    6-1-2: Which of the following creates an array of 10 doubles called prices?

  • int[] prices = new int[10];
  • We need double for money amounts in prices.
  • double[] prices = new double[10];
  • Yes correct!
  • double[] prices;
  • This declares the array but does not create it with new.
  • double[10] prices = new double[];
  • This is not the correct syntax.

coding exercise Coding Exercise

In the following code, add another array declaration that creates an array of 5 doubles called prices and another array of 5 Strings called items and corresponding System.out.println commands.

Note

Array elements are initialized to 0 if they are a numeric type (int or double), false if they are of type boolean, or null if they are an object type like String.

../_images/arrayIndicies.png

Figure 2: Two 5 element arrays with their values set to the default values for integer and object arrays.

6.1.2. Initializer Lists

Another way to create an array is to use an initializer list. You can initialize (set) the values in the array to a list of values in curly brackets { } when you create it, like below. In this case you don’t specify the size of the array, it will be determined from the number of values that you specify.

int[ ] highScores = {99,98,98,88,68};
String[ ] names = {"Jamal", "Emily", "Destiny", "Mateo", "Sofia"};

When you create an array of a primitive type (like int) with initial values specified, space is allocated for the specified number of items of that type and the values in the array are set to the specified values. When you create an array of an object type (like String) with initial values, space is set aside for that number of object references. The objects are created and the object references set so that the objects can be found.

../_images/intAndStringArrays.png

Figure 3: A primitive array and an object array

Arrays know their length (how many elements they can store). It is a public read-only field so you can use dot-notation to access the field (arrayName.length). Dot-notation is using variable name followed by a . and then the field (property) name or a method name. Try the following.

coding exercise Coding Exercise

Try running the code below to see the length. Try adding another value to the highScores initializer list and run again to see the length value change.

Note

Note that length is a field and not a method, unlike the String length() method, so you don’t add parentheses after length. However, if you use parentheses after length during the exam, you won’t lose any points.

exercise Check your understanding

    6-1-3: Which index is the last element in an array called highScores at?

  • highScores.length
  • Look at the example above when we were setting the values for the highScore array.
  • highScores.length - 1
  • Since the first element in an array is at index 0 the last element is the length minus 1.

6.1.3. Accessing Values in an Array

To access the items in your 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. An indexed variable like arrayname[index] can be used anywhere a regular variable can be used, for example to assign a new value or to get a value from the array like below.

// assign a new value 99 to the first element in the array
highScores[0] = 99;
// print the first element of the array
System.out.println( highScores[0] );

Note

The first value in an array is stored at index 0 and the index of the last value is the length of the array minus one (since the first index is 0). Use arrayname[index] to access array items.

exercise Check your understanding

6-1-4: Fill in the blank with code to access the cars array.

String[] cars = {“Honda”, “Volvo”, “BMW”};

// Access cars array to get Volvo

String v = ;

6-1-5: Fill in the blank with code to access the cars array.

String[] cars = {“Honda”, “Volvo”, “BMW”};

// Set the first item of the cars array to be Toyota

= “Toyota”;

If you want to keep track of the top 5 highest scores in a game and the names of the people with those scores, you could use two parallel arrays. One array could keep track of the scores and the other the names. You have to make sure you keep them in the same order so that the same index can be used to get correponding names and scores.

coding exercise Coding Exercise

Try out the following code which has two parallel arrays, highScores and names. Can you print out Mateo’s score? Can you change Sofia’s score to 97 using an assignment statement in the code? Can you change the arrays so that they have 6 elements and add your name and score and print them out? What happens if you try to access an element that is not there, for example at index 7?

Note

Using an index value outside of 0 - (length-1) will result in an ArrayIndexOutOfBoundsException being thrown.

One powerful feature in the array data abstraction is that we can use variables for the index! As long as the variable holds an integer, we can use it as an index.

// use a variable for the index
int index = 3;
System.out.println(  highScores[index] );

coding exercise Coding Exercise

Here’s a fun String array of image filenames. The following code displays an online image using an HTML tag. (Note that this just works in this Active Code window which interprets HTML. In other Java IDEs you would need to use Java Swing graphics instead). Run the code and see that it displays images[0] which is “cow.jpg”. The images array holds 5 images. Can you change the index variable’s value so that it print out the puppy image? Can you print out the reindeer? Try all of them! What indices did you need to use? Then try using a random number for the index instead. Remember that (int)(Math.random()*max) will return a number from 0 up to max. What’s the maximum number it can be for this array?

6.1.4. groupwork Programming Challenge : Countries Array

In this challenge, you will create a guide to different countries using arrays.

  1. Use the Active Code window below to create 4 parallel arrays and intialize them using initialization lists that represent the data below. Remember that the order of these arrays has to match so that you can use the same index and get corresponding values out.

  • Countries: China, Egypt, France, Germany, India, Japan, Kenya, Mexico, United Kingdom, United States

  • Capitals: Beijing, Cairo, Paris, Berlin, New Delhi, Tokyo, Nairobi, Mexico City, London, Washington D.C.

  • Languages: Chinese, Arabic, French, German, Hindi, Japanese, Swahili, Spanish, English, English

  • Filenames for map images: China.jpg, Egypt.jpg, France.jpg, Germany.jpg, India.jpg, Japan.jpg, Kenya.jpg, Mexico.jpg, UK.jpg, US.jpg

  1. Choose a random number using Math.random() and the length of one of the arrays and save it in a variable called index.

  2. Print out the country name, its capital, and its language, and the map image for that country using the random index to access the corresponding item in each parallel array. For the images, the printHTMLimage method has been given to get the image URL online and print it out as an HTML image.

6.1.5. Summary

  • Arrays represent collections of related data all of the same data type.

  • The size of an array is established at the time of creation and cannot be changed.

  • Arrays can store either primitive data or object reference data.

  • When an array is created using the keyword new, all of its elements are initialized with a specific value based on the type of elements:

    • Elements of type int are initialized to 0

    • Elements of type double are initialized to 0.0

    • Elements of type boolean are initialized to false

    • Elements of a reference type are initialized to the reference value null. No objects are automatically created.

  • Initializer lists can be used to create and initialize arrays.

  • Square brackets ([ ]) are used to access and modify an element in a array using an index.

  • The valid index values for an array are 0 through one less than the number of elements in the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException being thrown.

You have attempted of activities on this page
Next Section - 6.2. Traversing Arrays with For Loops