Arrays

Introduction

Programs constantly work with many values of the same kind: the marks of a class, the pixels of an image, the squares of a board. An array stores a fixed number of values of one type side by side, each reached by its index. Arrays are the simplest and fastest collection in Java, and the collections you will meet later are built on them.

How it works

An array is created with a size, or with its values:

int[] counts = new int[5];          // five zeros
int[] marks = {72, 45, 88, 91, 60}; // five given values

Elements are read and written by index, from 0 to length - 1: marks[0] is 72 and marks[marks.length - 1] is the last one. An index outside that range throws an ArrayIndexOutOfBoundsException while the program runs. The length is fixed when the array is created; to "grow" an array you make a bigger one and copy the elements across.

New arrays are filled with default values: 0 for numbers, false for booleans, and null for objects such as Strings, meaning "no object yet".

There are two ways to loop. The classic for (int i = 0; i < a.length; i++) gives you the index, which you need to change elements or compare neighbours. The enhanced for loop for (int x : a) visits each element in order and is clearer when you only read them.

The class java.util.Arrays has helpers: Arrays.toString(a) turns an array into text such as [1, 2, 3] (printing the array directly shows only a code), Arrays.sort(a) sorts it in place, Arrays.copyOf(a, n) makes a copy of length n, and Arrays.fill(a, v) fills it.

An array variable holds a reference to the array, not the elements themselves. int[] same = marks; makes a second name for the same array, so a change through one name is seen through the other. That is also why a method can change the elements of an array passed to it.

A two-dimensional array is an array of arrays: new int[3][4] is 3 rows of 4 columns, and grid[r][c] reaches one cell. Nested loops visit every cell, and grid.length is the number of rows.

Example

// Arrays: fixed-size lists of one type, sorting, copying, and grids.
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {72, 45, 88, 91, 60};
        int total = 0;
        for (int m : marks) total += m;
        int[] sorted = Arrays.copyOf(marks, marks.length);
        Arrays.sort(sorted);
        System.out.println(marks.length + " marks, total " + total + ", highest " + sorted[sorted.length - 1]);
        System.out.println(Arrays.toString(marks) + " -> " + Arrays.toString(sorted));
        int[] same = marks; // a second name for the same array
        same[0] = 100;
        System.out.println(marks[0]);
        int[][] grid = new int[3][4];
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 4; c++) grid[r][c] = r * c;
        }
        System.out.println(grid.length + " rows: " + Arrays.toString(grid[2]));
        String[] names = new String[2];
        boolean[] flags = new boolean[2];
        System.out.println(names[0] + " " + flags[1]); // the default values
    }
}
Open in compiler

Line by line

  1. The enhanced for loop adds up the marks.
  2. Arrays.copyOf makes a separate copy, and Arrays.sort sorts the copy, leaving marks as it was.
  3. same refers to the same array as marks, so changing same[0] changes marks[0].
  4. The nested loops fill each cell of the grid with r * c.
  5. New arrays start with defaults: null for Strings and false for booleans.

Expected result

5 marks, total 356, highest 91
[72, 45, 88, 91, 60] -> [45, 60, 72, 88, 91]
100
3 rows: [0, 2, 4, 6]
null false

In the real world

Arrays sit under almost everything: ArrayList keeps its elements in an array, images are arrays of pixels, and games store boards and maps in two-dimensional arrays. Performance-critical code, such as signal processing or physics simulations, uses primitive arrays because they are compact and fast to loop over.

Common mistakes

  • Using length as an index: a[a.length] is one past the end.
  • Printing an array directly, which shows something like [I@1b6d3586 instead of the values.
  • Copying an array with =, which copies only the reference.
  • Forgetting that a new String array is full of null, which throws NullPointerException when used.

Best practices

  • Loop with i < a.length, never a hard-coded number.
  • Use the enhanced for loop when you do not need the index.
  • Use Arrays.toString and Arrays.deepToString when printing for debugging.

Summary

Arrays hold a fixed number of values of one type, indexed from 0 to length - 1, with defaults of 0, false or null. Loops visit them, the Arrays class prints, sorts and copies them, two-dimensional arrays are arrays of arrays, and an array variable is a reference, so assignment shares the array.

Quick check

1. What is the last valid index of an array of length 5?
2. What does new String[3] contain?
3. After int[] b = a; b[0] = 9;, what is a[0]?
4. How do you print the values of an int array?

Key takeaways

  • An array has a fixed length and one element type; indexes run from 0 to length - 1.
  • Arrays.toString prints an array; Arrays.sort sorts it in place; Arrays.copyOf copies it.
  • An array variable holds a reference: assigning it makes a second name for the same array.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.