Arrays

Updated: 3 years ago

Check out other lessons in Learning the Java syntax

Now that we know how primitive types work, we move on to arrays. Arrays enable us to store multiple values inside one variable.

What are arrays?

Arrays are a collection of values with the same type that can be assigned to a single variable. Grouping up values is very important because you will soon realise that you'll have a lot of different variables that you need to handle and use. Arrays come in handy when you have data that's repeatable, or has some kind of a pattern. For example, hourly temperature readings are a great example of an array of ints.

 // Creating an array of ints 
 int[] dailyTemperature = new int[5];

We use [] to set the type to an array of ints. If you see [], start thinking arrays. To create a new array of values you have to do new int[5] which says that we want a new array that has a size of 5. The compiler will then create a new array with 5 indexes (positions) where we can store 5 int values.

// Adding values to an array 
dailyTemperature[0] = 24;
dailyTemperature[1] = 22;
dailyTemperature[2] = 21;
dailyTemperature[3] = 25;
dailyTemperature[4] = 24;

Now we can assign a value to an index inside an array. We access each index with dailyTemperature[4] where 4 is the index inside the array. The indexes starts at 0 so be careful with that. If you try to access an index that doesn't exist in an array, your application will crash and you will be told in big red letters that you messed up.

When you want to retrieve the value at a specific index, you can just do dailyTemperature[4] and you'll get the value of 24, where 4 is the index inside the array.

You can also do dailyTemperature.size() to get the size of the array. This will come in handy a bit later when we are going to use arrays with loops.

public class Main
{

    public static void main(String[] args)
    {  
        // Creating an array of ints 
        int[] dailyTemperature = new int[5];

        // Adding values to an array 
        dailyTemperature[0] = 24;
        dailyTemperature[1] = 22;
        dailyTemperature[2] = 21;
        dailyTemperature[3] = 25;
        dailyTemperature[4] = 24;

        // Display the size of the array
        System.out.println("We have " + dailyTemperature.size() + " values inside our array");

        // Access a specific index inside our array
        System.out.println("The first temperature is: " + dailyTemperature[0]);
    }
}
« Previous lesson:
Primitive types
» Next lesson:
Conditionals