Java Arrays Tutorial

In this Java tutorial we learn how to store multiple values of the same type in a single data container called an array.

We discuss how to declare and initialize an array literal, how to create a new array instance object as well as how to add, access and mutate elements in an array.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is an array

An array is a data container, like a variable. Unlike a variable though, it can store multiple values in a table-like structure.

As an example, consider a list of groceries. It would be cumbersome to store items in such a list as separate variables, as well as to access them one by one.

Example:
String groceryItem1 = "Milk";
String groceryItem2 = "Bread";
String groceryItem3 = "Cheese";

Instead, we use an array and store the all the items in a single data container. We can then access the container with a single identifier, as well as iterate through the elements inside.

Example:
 String groceryList[] = { "Milk", "Bread", "Cheese" };

If we’re working with a larger number of values, it’s better to store them in an array instead of declaring many variables. Arrays are stored together, in sequence in memory, and are accessed faster by the CPU.

How to declare an array literal in Java

The easiest, and most straightforward, way to create an array is by declaring an array literal.

To declare an array literal we start by giving it a type. Arrays can only store elements of a single type, we cannot have, say, strings and integers mixed together.

Then, we give the array a name and postfix it with open and close square brackets. The brackets indicate to the compiler that we’re declaring an array, not a variable.

Syntax:
 type name[];

This will create an empty array that we can add values to.

Example:
public class Program {
    public static void main(String[] args) {

        // array declaration
        String user[];
    }
}

How to instantiate an array with the new keyword in Java

Because an array is an object, we can create a new object instance of an array by using the new keyword.

First, we specify the array type, name and square brackets. Then we add the assignment operator, followed by the keyword new and the type and brackets again.

This time however, we can explicitly specify the amount of elements the array can hold between the second pair of brackets.

Syntax:
 type name[] = new type[number_of_elements];
Example:
public class Program {
    public static void main(String[] args) {

        // declare new array object
        // with 4 empty elements
        String user[] = new String[4];
    }
}

In the example above, we create a new string array that can hold 4 values.

The 4 elements are initialized with null, which represents the absense of a value.

Example:
public class Program {
    public static void main(String[] args) {

        // declare new array object
        // with 4 empty elements
        String user[] = new String[4];

        for (String i : user) {
            System.out.println(i);
        }
    }
}

The example above will print the 4 values to the console. Java automatically gives them a value of null.

Output:
null
null
null
null

How to initialize an array with values in Java

To initialize an array we specify the type, name and square brackets, followed by an assignment operator and a code block. Lastly, we terminate the code block with a semicolon.

Inside the code block we specify the values we want the array to hold, separated by a comma.

Syntax:
type name[] = {

    value,
    value,
    ...
};
Example:
public class Program {

    public static void main(String[] args) {

        // array initialization
        String user[] = { "John", "Jane", "Jack", "Jill" };
    }
}

The array is like a table with a single row, but multiple columns. If we consider the example above, it would look like this.

JohnJaneJackJill

How to access array elements with the indexer in Java

To access an array element (a single value in the array), we use the indexer.

When we create an array, each value is assigned to a corresponding number, its index. If we think about an array as a table, we would add another row with numbers, starting at 0.

0123
JohnJaneJackJill

These numbers form the index. When we want to access a specific element, we provide the compiler with that element’s corresponding index number.

It’s important to note that any collection with a numerical index, will always start at 0, not at 1.

To use the indexer, we simply add the index number between square brackets, after the array name.

Syntax:
 array_name[index];
Example:
public class Program {
    public static void main(String[] args) {

        // initialize array
        String user[] = { "John", "Jane", "Jack", "Jill" };

        // access first element (0)
        // in 'user' array
        System.out.println( user[0] );
    }
}

In the example above, we access element number 0 in the array. Because the index starts at 0, it prints the first element ‘John’ to the console.

How to access array elements with a loop in Java

Arrays typically have many values and so it makes more sense to access its values within a loop.

Java makes it easy for us to access values in array by providing us with the foreach loop, also known as the enhanced for loop.

The foreach loop will count all the elements in the array, then iterate over them. We provide a temporary variable in the loop’s header that we can use to access the current array element value.

Syntax:
for (value_type temporary_variable : array_name) {

    // use temporary_variable to
    // access current iteration's
    // value
}

The header reads as follows: for each value in 'array_name', store the value in 'temporary_variable', then execute the code block.

The temporary variable’s type must be the same as the array type.

Example:
public class Program {
    public static void main(String[] args) {

        // init string array
        String user[] = { "John", "Jane", "Jack", "Jill" };

        // loop over all elements in
        // 'user' array, access the
        // element value with 'i'
        for (String i : user) {

            System.out.println(i);
        }
    }
}

In the example above, we have a string array, so our temporary variable’s type must also be a string.

Then, we tell the foreach loop to iterate over the ‘user’ array. Each time it loops, it will store the current element’s value in ‘i’, which we then print to the console.

The loop automatically stops when there are no more elements to iterate over.

How to change array elements in Java

Changing array elements is simple, we use the indexer to specify the element and assign a new value to it with the assignment operator.

Syntax:
 name[index] = new_value;
Example:
public class Program {
    public static void main(String[] args) {

        // init string array
        String user[] = { "John", "Jane", "Jack", "Jill" };
        System.out.println(user[0]);

        // mutate the value
        // at element 0
        user[0] = "John Doe";

        System.out.println(user[0]);
    }
}

In the example above, we change the name in the first array element from “John” to “John Doe”. The compiler overwrites the previous value with the new one we provide.

How to add elements to an empty array in Java

To add elements to an empty array, we use the indexer to specify the element and assign a value to it with the assignment operator.

Syntax:
 name[index] = value;
Example:
public class Program {
    public static void main(String[] args) {

        // declare empty array
        String filmList[] = new String[10];

        // add value
        filmList[0] = "The Godfather";
        filmList[1] = "Star Wars: Episode V";
        filmList[2] = "The Dark Knight";
        filmList[3] = "Pulp Fiction";
        filmList[4] = "Back to the future";
        filmList[5] = "Alien";
        filmList[6] = "Fight Club";
        filmList[7] = "Die Hard";
        filmList[8] = "Jurassic Park";
        filmList[9] = "Inception";

        System.out.println("Top 10 movies of all time:");
        System.out.println("");
        for (String i : filmList) {
            System.out.println(i);
        }
    }
}

Unfortunately, there’s no shortcut to add elements to an array dynamically. If we want to do that, we would have to use another collection type like an ArrayListOpens up in a new page .

Output:
Top 10 movies of all time:

The Godfather
Star Wars: Episode V
The Dark Knight
Pulp Fiction
Back to the future
Alien
Fight Club
Die Hard
Jurassic Park
Inception

Summary: Points to remember

  • An array is a data container that can store more than one value in a single container.
  • We declare an array literal by adding square brackets after its identifier.
  • We instantiate an array object by using the new keyword and an extra type with square brackets.
    • When we instantiate an array, we can specify its size (the number of elements it can hold).
  • We initialize an array literal by providing it with multiple, comma separated values between curly braces.
  • We access array elements with their corresponding index number between square brackets.
  • To access elements in an array easily, we typically use the foreach (enhanced for) loop.
  • To change the value of a single element, we assign a new value to it.