Card 01/ 08

ConceptDifficulty: Beginner1 min

Java Arrays: A Fixed Number of Values Under One Name

Seven variables called day1 to day7 work until something has to loop over them.

An array is one variable holding a fixed number of values of one type, each reached by its position, called its index. The type and the number of slots are decided when the array is created and never change afterwards.

You need the midday temperature for each of the last seven days. Seven variables called day1 to day7 work until something has to loop over them, and nothing can loop over seven separate names. One array holds all seven:

java
double[] temperatures = new double[7];

temperatures[0] = 14.5;
temperatures[6] = 11.0;

double[] is read as "array of double", and temperatures[0] is the slot at index 0. Two things are decided the moment that array is created. Its type: double, and nothing else will go in it. And its length: seven, permanently. An array cannot grow, shrink or change type after the line that made it.

What an array fixes and what it leaves open
Fixed at creationFree to change
The element typeThe value in any slot
The number of slotsHow many slots you have written to

Because every slot has a number, a loop can visit them all: a counter running from 0 up to the length reaches each day in turn, which is exactly what seven separate variables could not offer.

So an array is the right shape when you know how many things there will be and they are all alike. The moment the count is not known ahead of time, you want something that can grow, which is what a List is for, and what arrays sit underneath.

← → move through sections and cards