Card 02/ 08

WalkthroughDifficulty: Beginner2 min

Creating an Array: Declare, Allocate and Fill

Three steps Java lets you write on one line, which is why the one-line version confuses.

Creating a Java array takes three steps: declare a variable that can hold an array, allocate the slots with new, and write values into them. Java lets you write all three on one line, and seeing them separately explains why a new array is already full of zeros or of null.

Before you start you need the element type and the number of slots. The steps below build an array of seven daily temperatures, then show the one-line form:

Creating and filling an array of daily temperatures

Declare the variable

java
double[] temperatures;

This makes a variable that can hold the address of an array of double. There is no array yet, and temperatures holds nothing. Reading temperatures[0] here fails to compile, because the compiler can see nothing has been assigned.

Allocate the slots

java
temperatures = new double[7];

new double[7] creates the array and returns its address, which is what temperatures now holds. Every slot already has a value: 0.0, because that is the default for double. An array of String would be full of null instead.

Fill the slots

java
for (int day = 0; day < temperatures.length; day++) {
    temperatures[day] = readingFor(day);
}

temperatures.length is a field on the array, a value stored with it, not a method, and it is the length that was fixed when the slots were allocated. Using it rather than writing 7 keeps the loop correct if the array size changes.

Collapse it, when you know the values

java
double[] temperatures = {14.5, 16.0, 12.5, 13.0, 15.5, 12.0, 11.0};

The brace form does all three at once and takes the length from how many values you wrote. It only works on the line that declares the variable; assigning {...} to an existing variable needs new double[] {...} instead.

You know it worked when temperatures.length is 7 and no slot holds a value you did not mean. The step to remember is allocation: every array of a primitive type (such as int or double, which hold values directly) comes out full of zeros and every array of an object type comes out full of null, so an array is never uninitialised. It is initialised to something you may not have wanted.