Skip to content

Arrays

Estimated time to read: 2 minutes

Array Overview

Arrays hold elements of a type and allow you to define a grouping of primitives or objects with the same name.

An array has a size attached to it. In Java, arrays are fixed sizes by default.

An array only holds objects (primitives or references / pointers)

Each entry in the array is referenced by a number known as the 'index' ranging to zero to one less than the size of the array, n-1.

Defining an array

Arrays in Java are objects. You access arrays through a reference. To create an array reference, you sate the type followed by square brackets and a name:

int [] myIntArray;

This tells the compiled that we want an array of ints. It doesn't say how many or what their values will be yet!

Initialising an array

To initalise an array, use the 'new' operator and another set of square brackets. For example, the following defines an integer array with the name of myIntArray and 25 blank integer entries.

int myIntArray = new int[25];

myIntArray is a reference to an array of ints, in this instance, 25.

Initialisation Short Cuts

Java will accept the following syntax to create an array and set its length and values all in one statement:

int[] myIntArray = {11,12,13,14,15};

The above example creates an int based array with a length of 5 and sets the value of each of the index indices.

Array Lengths

Java provides every array you create with a single attribute named length. To put the length of 'myIntArray' into an int declared as 'x', the following can be used:

int x = myIntArray.length

Setting a value in an array

Assign the value of '42' to the first entry into the array myIntArray[0] = 42

Arrays and Objects

Arrays are objects and can hold any of the eight primitive types.

You can also create them from any Java object reference. For example, an array of Strings: String[] pets {"Fido", "Rex", "Princess"};

Array structure

Screenshot 2022-07-05 at 19.32.13.png