CodeMIRAI
0 XP

Arrays

2 min read 6 runnable examples Quiz included

Creating arrays

Java
public class Main {
    public static void main(String[] args) {
        int[] scores = {85, 92, 78, 95, 88};
        String[] names = new String[3];    // three empty slots
        names[0] = "Asha";
        names[1] = "Leo";

        System.out.println(scores[0]);        // 85
        System.out.println(scores.length);    // 5
        System.out.println(names[2]);         // null: never filled
        scores[2] = 80;                       // change an element
        System.out.println(scores[2]);        // 80
    }
}
  • Indexes start at 0, so the last element is at length - 1.
  • An array's size is fixed when it's created.
  • New arrays are filled with defaults: 0 for numbers, false for booleans, null for objects.

Looping over an array

Java
public class Main {
    public static void main(String[] args) {
        int[] scores = {85, 92, 78, 95, 88};
        int total = 0;
        int best = scores[0];
        for (int s : scores) {
            total += s;
            if (s > best) best = s;
        }
        double average = (double) total / scores.length;
        System.out.println("Total " + total + ", best " + best + ", average " + average);

        for (int i = 0; i < scores.length; i++) {
            System.out.println("Student " + (i + 1) + ": " + scores[i]);
        }
    }
}

Use the enhanced for when you just need the values, and the counting for when you need the index too.

Going out of bounds

Java
public class Main {
    public static void main(String[] args) {
        int[] data = {1, 2, 3};
        System.out.println(data[3]);
    }
}

There's no data[3] in a three-element array, so Java stops with an ArrayIndexOutOfBoundsException instead of quietly reading whatever is in memory next, as C would.

The Arrays class

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = {42, 7, 19, 3, 25};
        System.out.println(Arrays.toString(nums));          // [42, 7, 19, 3, 25]
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));          // [3, 7, 19, 25, 42]
        System.out.println(Arrays.binarySearch(nums, 19));  // 2: its index, in a sorted array
        int[] longer = Arrays.copyOf(nums, 7);
        System.out.println(Arrays.toString(longer));        // [3, 7, 19, 25, 42, 0, 0]
        int[] sevens = new int[4];
        Arrays.fill(sevens, 7);
        System.out.println(Arrays.toString(sevens));        // [7, 7, 7, 7]
    }
}

Printing an array directly, System.out.println(nums), shows something unhelpful like [I@1b6d3586. Arrays.toString prints the contents.

2D arrays

Java
public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println(grid[1][2]);    // row 1, column 2: 6
        for (int[] row : grid) {
            for (int value : row) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

A 2D array is an array of arrays: grid[1] is the whole second row, and grid[1][2] an element in it.

Array variables are references

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = a;            // b refers to the same array
        b[0] = 99;
        System.out.println(Arrays.toString(a));    // [99, 2, 3]

        int[] c = a.clone();    // a real copy
        c[1] = 0;
        System.out.println(Arrays.toString(a) + " " + Arrays.toString(c));
    }
}

Assigning an array to another variable doesn't copy it: both names refer to the same array. Use clone() or Arrays.copyOf to make a real copy.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.