jario_
Back to overview

Chapter 4

Arrays

A variable stores one value. For ten measurements or the seven days of the week, you'd need ten or seven variables. An array groups many values of the same type under one name, and a loop lets you go through all of them.

Create, read, change

Square brackets after the type make it an array: int[], String[], double[]. There are two ways to create one:

  • with fixed values: String[] fruits = {"Apple", "Banana", "Cherry"};
  • with a size: int[] zeros = new int[4]; (all slots are then 0, for String null)

Every slot has a number, its index. Counting starts at 0: fruits[0] is the first element, fruits[fruits.length - 1] the last. length is the number of slots. It's fixed when the array is created and never changes.

Arrays.toString(...) (with import java.util.Arrays;) turns an array into readable text.

You can change the code and run it again.

Arrays and loops

The classic form runs an index from 0 to length - 1. With it you can read, write and even go backwards.

If you don't need the index, the for-each loop is shorter: for (int number : numbers) means “for each number in numbers”. It only reads. You can't change values in the array with it.

You can change the code and run it again.

The first number of the input says how many numbers follow. Try a different count.

Two-dimensional arrays

An array can itself contain arrays, for example for a table, a game board or a cinema hall. int[][] points is an array of rows, each row an int[]. points[1][2] is row 1, column 2 (both counted from 0). points.length is the number of rows, points[row].length the length of one row.

You can change the code and run it again.

Common mistakes

  • Index outside the array

    The last element has the index length - 1. With i <= numbers.length the loop reaches one step too far, and the program crashes:

    ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

    The condition needs <, not <=.

  • Printing an array directly

    System.out.println(numbers) doesn't print the contents but something like [I@1b6d3586. For the contents, use Arrays.toString(numbers).

  • Assigning is not copying

    An array variable points to the array, it doesn't contain it. After int[] b = a; both point to the same array:

    int[] a = {1, 2, 3};
    int[] b = a;
    b[0] = 99;
    System.out.println(a[0]); // 99
  • Array created too small

    An array's size can't be changed afterwards. If you only learn the count from the input, read it first and create the array afterwards: int[] numbers = new int[n];.