Chapter 7 - Java for Beginners Course

Arrays - Declaration and Creation

Arrays are a built-in data structure in the Java language that allow us to store a fixed number of objects of the same type.

A typical analogy of an array is thinking of a number of boxes that are lined up one after the other, and you can store objects of the same type in them. For example, an array of 4 String objects would be represented graphically like this:

Example of an array of Strings of 4 elements

Elements in the array have a position or index. In Java, similar to other programming languages, the elements in the array start from index 0 (a.k.a zero-based indexing).

Defining an array

We define an array by using square brackets [] after the type of object we want to store in the array, as follows:

Type[] anArray;

You can define arrays of any type, including primitive types, for example, we could do int[] anArrayOfNumbers;.

For our example of the String array in the figure above, we’d do:

String[] anArray;

Here we are just declaring a variable named anArray that is of type "array of String". However, we haven’t yet created the array in memory yet.

Creating a new array

Arrays are objects in Java, so, in the same way we create a new object, we can use the new operator to create a new array, also using the square brackets [] as follows:

Type[] anArray = new Type[size];

When we create the array, we must define its length/size. This size is fixed for that array and cannot be changed.

If we need a shorter/larger array, we’d need to create a new array with the required size and copy the elements across.

For the String array example at the top:

String[] anArray = new String[4];

Accessing values in the array

In order to access an element in the array, either to write or read their value, we make use of their index/position in the array. For example, to assign a value to the elements in the String array we would do the following:

anArray[0] = "This is";
anArray[1] = "an array";
anArray[2] = "of Strings";
anArray[3] = null;

In order to read a value, we’d use the same syntax, for example:

String firstElement = anArray[0];

Initialize shortcut

Java provides a shortcut way to define, create and initialize an array at the same time, by defining the initial values of the elements in curly braces ({}) when creating the array, like this:

String[] anArray = { "This is", "an array", "of Strings", null };

Length of an array

Arrays in Java have a property called length which you can use to retrieve the number of elements the array was created with. For example, you could do the following:

In the example code run the JavaBasicArraysApp
String[] anArray = { "This is", "an array", "of Strings", null };
System.out.println("The length of the array is: " + anArray.length);
String lastElement = anArray[anArray.length - 1];
System.out.println("The last element of the array is: " + lastElement);

Output:

The length of the array is: 4
The last element of the array is: null

As Java keeps track of the length of the array for us (some other languages do not), it also performs automatic checks when we access an element of the array to ensure it is inside the defined bounds.

For example, the String array above has length = 4, so the index value should be between 0 and 3. If we try to do the following:

anArray[10] = "Index 10";

We’ll get an exception java.lang.ArrayIndexOutOfBoundsException: 10 at runtime that informs us that the given index 10 isn’t valid.

A note about array declarations

In Java, the following two ways of declaring an array are valid:

Type[] anArray;
Type anArray[];

Both yield the same result. However, the second approach is discouraged and the first approach Type[] anArray has become the standard.

Multi-dimensional arrays

It’s important to note that the example arrays we’ve mentioned above are one-dimensional arrays. However, you can also define arrays with more dimensions, for example a two dimensional array can be defined as:

int[][] matrix = {
        { 1, 2 },
        { 3, 4 }
};
System.out.println("The element in the first row and first column is: " + matrix[0][0]);

Output:

The element in the first row and first column is: 1

We’re using the shortcut way of initializing the array, and you’ll notice we have nested curly brackets {}. In this case, we end up with an 2D array that would have the following structure:

Example of a two dimensional array

For a 2D array, it’s common to think about them as rows and columns in a spreadsheet where each dimension is zero-based indexed.

In our example, all rows have the same number of columns. This isn’t required, you can have arrays with rows that have different numbers of columns.