Skip to the workspace
Pebellslearn by building
Control Flow, Arrays and Strings  ›  Lesson

Arrays: A Fixed Row of Boxes

Arrays 13 minAn array holds a fixed number of values of one type, reached by an index that starts at zero and ends at length minus one.

java / Arrays: A Fixed Row of Boxes

Explore each scene at your own pace.

01 · The rule

The rule

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 price

What 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].
  • length is 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).
  • length has 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 0

Two behaviours surprise people:

  • Reading pricesCents[3] compiles, but at run time the JVM throws an ArrayIndexOutOfBoundsException.
  • System.out.println(pricesCents) prints something like [I@5ca881b5, not the values. Use Arrays.toString(pricesCents) from java.util.Arrays to 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.