Card 02/ 08
All 8 cards
WalkthroughDifficulty: Beginner1 min
From a Declaration to a Filled Array of Seven Totals
Creating an array is three separate things that Java lets you write on one line, which is why the one-line version is confusing the first time. Here it is as three steps, and then collapsed.
Creating and filling an array of daily totals
Step 1 of 4
Declare the variable
double[] totals;This makes a variable that can hold the address of an array of double. There is no array yet, and totals holds nothing. Reading totals[0] here fails to compile, because the compiler can see nothing has been assigned.
Allocate the slots
totals = new double[7];new double[7] creates the array and returns its address, which is what totals 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
for (int day = 0; day < totals.length; day++) {
totals[day] = salesFor(day);
}totals.length is a field on the array, not a method, and it is the length that was fixed in step two. Using it rather than writing 7 means the loop stays correct if the array size changes.
Collapse it, when you know the values
double[] totals = {240.50, 180.00, 0.0, 412.25, 99.99, 310.10, 98.00};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.
The run to remember is the middle one. Every array of a primitive type 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.