Arrays: A Fixed Row of Boxes
Brew Bar's menu board shows three sizes: small, medium and large. Keeping three separate variables for their prices works until someone asks for "the price of every size" or "the most expensive one". An array keeps related values together, in order, under one name.
The rule
An array is a fixed row of boxes, numbered from zero.
int[] pricesCents = {250, 300, 350}; // small, medium, large
System.out.println(pricesCents[0]); // 250
System.out.println(pricesCents.length); // 3
pricesCents[2] = 360; // change the large priceWhat each part means:
int[]is the type: an array of ints. Every element has that same type.- Index from zero. The first box is
[0], the last is[length - 1]. lengthis fixed when the array is created. You cannot add a fourth box later; you would need a new array, or a list (coming later in the course).lengthhas no brackets. For arrays it is a field,pricesCents.length. Strings use a method,name.length().
You can also create an empty array of a given size. Its boxes start with default values: 0 for numbers, false for booleans and null for references.
int[] cupsSold = new int[7]; // one box per weekday, all 0Two behaviours surprise people:
- Reading
pricesCents[3]compiles, but at run time the JVM throws anArrayIndexOutOfBoundsException. System.out.println(pricesCents)prints something like[I@5ca881b5, not the values. UseArrays.toString(pricesCents)fromjava.util.Arraysto get[250, 300, 360].
An array variable holds a reference to the row of boxes. int[] copy = pricesCents; does not copy the boxes; both names now point at the same row.
The shortcut
For any index question, draw the row with its numbers underneath, starting at 0. The last valid number is always length - 1.
Draw the row
Values 250, 300, 360 sit above indexes 0, 1, 2. The length is 3.
Drills
Answer fast — trust the rule.
With int[] pricesCents = {250, 300, 350};, what is pricesCents[pricesCents.length - 1]?
What does new int[3] contain?
What happens when the program reads pricesCents[3] on that three-element array?
int[] copy = pricesCents; copy[0] = 0; What is pricesCents[0] now?
Remember
- An array is a fixed row of boxes, numbered from zero, with
.lengthand no brackets. - Draw the row with its indexes; the last one is
length - 1. - Traps: index
length, printing the array directly, and thinking=copies the boxes.
