Arrays: A Fixed Row of Boxes
An array holds a fixed number of values of one type, reached by an index that starts at zero and ends at length minus one.
Track array indexes, fixed length and references to the same array.
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.