Card 01/ 08

ConceptDifficulty: Beginner1 min

One Name for Twenty Values, and the Number That Picks One

You need the sales total for each of the last seven days. Seven variables called day1 to day7 works until something has to loop over them, and nothing can loop over seven separate names.

An array is one variable holding a fixed run of values of one type, each reachable by its position.

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

totals[0] = 240.50;
totals[6] = 98.00;

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

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.