This site is retired and is no longer updated since November 2021. Please visit our new website at https://www.teamscode.org for up-to-date information!
Arrays

So far, we have worked pretty much exclusively with simple primitive variables, such as integers and doubles, that each can store one value. In this lesson, we will cover arrays, which can store multiple values.

Imagine having a class of three students, each of whom has just taken the final exam of the class. The teacher has graded each person’s test and wants to store that data somewhere. Assuming each student’s grade is an integer between 0 and 100, you can imagine storing this data in the following way:

    int student1 = 95;

    int student2 = 78;

    int student3 = 83; 

However, this is obviously not very efficient. Now imagine if you had to store this kind of data for thousands, or even millions of students. This would clearly be a disaster. This is where more advanced data structure come into play. An array can store multiple values under a single declared instance of type array. It can sometimes be thought of as a numbered list.

The syntax for declaring an array is simple:

    int num; // This is how to create an normal integer variable. 

    int[] array; // This is how to create an array of integers. 

In the two lines of code above, we have created two new variables. The array is created in a similar way to the int, except that there is a pair of square brackets [] after specifying the int type. This tells the computer that this variable is an array and does not just hold one value of type int, but can hold multiple values. Currently, neither one holds any values because they have not been initialized. To create an array with initial values, do the following:

    array = {5, 6, 7}; // Assigns the array three values: 5, 6, and 7. 

The array is initialized by having values separated by commas and surrounded by curly brackets. Here are some more examples of declaring an array:

    int[] arr1 = {5, 6, 7};     // Joining the two steps together into one line. 

    int[] arr2 = {};            // You can create an array with no values. 

    String[] arr3 = {"hi"};     // An array that stores strings. 

    Scanner[] arr4;             // You can even have an array of Scanners!

Going back to the first example of storing student grades, we can create an array for that data by doing the following:

    int[] studentGrades = {95, 78, 83};

Now that we have stored the data, what can we do with it? Let’s try accessing some of the data stored in the array. If we want to get the score of Student 1, we will have to look for the first value in the array.

    int score = studentGrades[0]; // Assigns score the first value in the array. 

Similar to when creating an array, you need to include square brackets [] when you want to access a specific value in the array. However, when accessing elements, you need to include an integer value (known as an index) between 0 (inclusive) and the size of the array (exclusive) between the square brackets to specify which value you want. The index 0 would give you the first element in the array, the index 1 would give you the second, and so on, all the way to the end, where the index n - 1 will give you the nth and final element in the array, where n represents the size of the array. So, if the size of the array was 20, the index 19 would give you the last value (20th) in that array.

In the example with the student grades, this table shows what value is at each index:

studentGrades[0] studentGrades[1] studentGrades[2]
95 78 83

If we want to modify values in an array, it is pretty much the exact same as modifying the value of a normal primitive variable. Let’s say the teacher was very generous with curving the students’ grades.

    studentGrades[0] = 100;     // changed from 95 to 100

    studentGrades[1] += 20;     // changed from 78 to 98

    studentGrades[2]++;         // changed from 83 to 84

All of these operations are exactly the same as we have learned. The only difference is that we specify the index of the array to tell the computer which value we want changed.

If we want to give everyone in the class a 10 point boost to their scores, we can use a for loop to traverse through the whole array, regardless of its size. This way, we avoid having to manually go through each index of the array, which would be terribly inefficient the larger the array becomes.

    for (int i = 0; i < studentGrades.length; i++) {

        studentGrades[i] += 10;

    }

Notice the .length in the for loop header. This gives us the size of the array and allows us to traverse through all of the indices of the array. Even if you know the size of the array (such as 3 for studentGrades), it is always best to use .length in these cases or else you put your code at risk if the array ever changes size.

Also, you must remember that since indices start at 0, the last element in an array would not be at arr[arr.length] but instead at arr[arr.length - 1].

Earlier in this lesson, we covered how to create an array with initial values by doing something like this:

    int[] arr = {5, 6, 7};

However, most of the time, we don’t want to create an array with initial values in it, or we want to create a really large array that would be impossible to go through and manually specify values. For example, what if we wanted to create an array of size 1000 that stored the numbers 0 through 999?

    int[] arr = {0, 1, 2, 3, 4, ... 997, 998, 999}; 

This would be one way to do it, but obviously very inefficient. This is where a new way of initializing arrays comes in. The more common way of creating an array is by specifying the size of the array upon initialization, which then automatically creates an array of that size with default values at each index (default for integers: 0, default for booleans: false, etc.). Then, once you create your array of a given size, you can use a for loop to efficiently assign values to each index. Here is how you initialize an array in this way:

    int[] arr1 = new int[1000];         // Creates an int array of size 1000

    double[] arr2 = new double[30];     // Creates a double array of size 30

    // and so on... 

The first part (to the left of the equals sign) is the same, but the right side is different. Similar to how in the last lesson, to create a new Scanner, you have to use the new keyword, creating an array is the same. After that, you retype the same thing with the type of data you’re storing (int, double, String) followed by square brackets (int[], double[]), although this time you have an integer in between the brackets to specify the size of the array. An array has a fixed size, so once you specify this size, there is no way to change it without creating a new array by doing the = new int[/* *SIZE* */] syntax.

So, to create an array storing the numbers 0 to 999, all we have to do is the following:

    int[] arr = new int[1000];

    for (int i = 0; i < arr.length; i++) {

        arr[i] = i;

    }

If you ever need to print out an array in a nice format, use the following code (first, add import java.util.Arrays to the beginning of your file):

    System.out.println(Arrays.toString(arr));

    // Output: [0, 1, 2, 3, ... 998, 999]

The last thing we are covering in this lesson is 2D arrays. Here is an example 2D array:

    int[][] arr = {{1, 2}, {8, 5}, {2, 4, 6}};

    // This can be visualized as: 

    //  1 2

    //  8 5

    //  2 4 6

We can create 2D arrays in Java simply by having two pairs of square brackets. The first square brackets represent the number of rows and the second pair represents the number of columns in the array. Here are a few examples:

    int[][] arr = new int[2][3]; // Creates an array of 2 rows by 3 columns

    System.out.println(arr.length + " " + arr[0].length); // Output: 2 3

    // Traverses through the whole 2D array

    for (int i = 0; i < arr.length; i++) {

        for (int j = 0; j < arr[i].length; i++) {

            System.out.print(arr[i][j] + " ");

        }

        System.out.println();

    }

2D arrays are very useful in many ways when a numbered list simply isn’t good enough to represent the data that you have. They can be used to represent grids, matrices, images, and much, much more. While they may seem overly complicated at first, you will quickly be able to understand how they work with practice.

Arrays are a fundamental part of programming in any language and it is important that you fully understand how the work. In the next lesson, we will be continuing to work with arrays.

Lesson Quiz

1. What is the output to the console?

    int[] arr = new int[5];

    for (int i = 1; i < arr.length; i++) {

        arr[i] = arr[i - 1] + i;

        System.out.print(arr[i] + " ");
    }
a. 0 1 2 3 4
b. 0 1 3 6 10
c. 1 3 6 10

2. What is the output to the console?

    int[][] arr = {{1, 2, 3}, {10}, {}, {4, 8}};

    for (int i = 0; i < arr.length; i++) {

        for (int j = 0; j < arr[i].length; j++) {

            System.out.print(arr[i][j] + " ");
        }

    }
a. 1 2 3 10 4 8
b. 1 10 4 2 8 3
c. Error

Written by Alan Bi

Notice any mistakes? Please email us at learn@teamscode.com so that we can fix any inaccuracies.