Java Arrays

An array is a fixed-length, numbered row of values of one type, and it is the structure that ArrayList, HashMap and String are built on. This page explains how arrays are laid out in memory, then shows creating, copying, two-dimensional arrays, the java.util.Arrays helpers, how much memory they save over lists, and the traps that come from arrays being objects.

Contents

What an array is

An array is a single object that holds a fixed number of elements of one type, stored one after another in memory. Each element is reached by its index, counted from 0. Because every element has the same size and they sit side by side, the JVM finds element i by arithmetic: start of the array plus i times the element size. That is why reading a[500000] takes the same time as reading a[0].

Three properties follow from this layout and explain most of how arrays behave:

  • The length is fixed when the array is created. "Adding" to an array means creating a bigger one and copying, which is what ArrayList does for you.
  • An array is an object. A variable such as int[] a holds a reference to it, so assigning or passing an array never copies its elements.
  • Primitive arrays store the values themselves, not references to objects, which makes int[] several times smaller than a list of Integer.
Declaring and creating arrays
CodeResult
int[] a = new int[4];4 elements, all 0
String[] s = new String[2];2 elements, both null
int[] p = {2, 3, 5};Length and values from the initializer (only in a declaration)
p = new int[] {7, 11};The same, anywhere, for example as a method argument
int[][] g = new int[3][4];3 rows of 4 zeros
int a[] = new int[4];Also legal (C style), but int[] a is the usual Java form

New elements always get a default value: 0 for numbers, '\u0000' for char, false for boolean and null for objects. Java never gives you uninitialized memory.

Creating, reading and the reference trap

The program creates arrays three ways, sums one with a for-each loop, goes past the end on purpose, and then shows what assignment really copies. The prime numbers are used because their sum, 28, is easy to check.

Java
import java.util.Arrays;

public class ArrayBasics {

    public static void main(String[] args) {
        int[] scores = new int[4];                 // fixed length, filled with 0
        String[] names = new String[2];            // filled with null
        int[] primes = {2, 3, 5, 7, 11};           // initializer sets length and values

        scores[0] = 90;
        scores[3] = 75;
        System.out.println("scores: " + Arrays.toString(scores) + ", length " + scores.length);
        System.out.println("names:  " + Arrays.toString(names));
        boolean raw = primes.toString().startsWith("[I@");
        System.out.println("primes.toString() starts with [I@: " + raw);

        int sum = 0;
        for (int p : primes) {
            sum += p;
        }
        System.out.println("sum of primes: " + sum);

        try {
            primes[5] = 13;                        // no index 5 in a length-5 array
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }

        // Arrays are objects: = copies the reference, not the elements
        int[] alias = primes;
        int[] copy = Arrays.copyOf(primes, primes.length);
        alias[0] = 99;
        System.out.println("primes after alias[0] = 99: " + Arrays.toString(primes));
        System.out.println("copy is unaffected:         " + Arrays.toString(copy));

        // == compares references; Arrays.equals compares elements
        int[] a = {1, 2};
        int[] b = {1, 2};
        System.out.println("a == b: " + (a == b) + ", Arrays.equals: " + Arrays.equals(a, b));
    }
}

Output:

Output
scores: [90, 0, 0, 75], length 4
names:  [null, null]
primes.toString() starts with [I@: true
sum of primes: 28
Index 5 out of bounds for length 5
primes after alias[0] = 99: [99, 3, 5, 7, 11]
copy is unaffected:         [2, 3, 5, 7, 11]
a == b: false, Arrays.equals: true
  • The length is read with array.length, a field, not a method; for strings it is length() and for lists size().
  • Valid indexes are 0 to length - 1. Index 5 in a 5-element array throws ArrayIndexOutOfBoundsException, whose message names both the index and the length.
  • Printing an array directly calls Object.toString, which gives the type code and a hash such as [I@1b6d3586 ([I means "array of int"). To see the elements, use Arrays.toString.
  • alias = primes copied the reference, so changing alias[0] changed primes too. Arrays.copyOf made a separate array, which kept the old values.
  • a == b is false for two arrays with the same contents, because == compares references. Arrays.equals compares the elements.

Copying arrays

There are four ways to copy an array, and one detail that catches many people: copies of object arrays are shallow. The program copies a small int[] each way, shifts elements inside one array, and then shows what is shared between an array of objects and its copy.

Java
import java.util.Arrays;

public class CopyingArrays {

    public static void main(String[] args) {
        int[] source = {10, 20, 30, 40, 50};

        // Four ways to copy a whole or partial array
        int[] a = source.clone();
        int[] b = Arrays.copyOf(source, source.length);
        int[] c = Arrays.copyOfRange(source, 1, 4);         // indexes 1, 2, 3
        int[] d = new int[source.length];
        System.arraycopy(source, 0, d, 0, source.length);
        System.out.println("clone:           " + Arrays.toString(a));
        System.out.println("copyOf:          " + Arrays.toString(b));
        System.out.println("copyOfRange 1-4: " + Arrays.toString(c));
        System.out.println("arraycopy:       " + Arrays.toString(d));

        // System.arraycopy handles overlap: shift right by one to make room at index 0
        int[] shift = {1, 2, 3, 4, 0};
        System.arraycopy(shift, 0, shift, 1, 4);
        shift[0] = 99;
        System.out.println("shifted right:   " + Arrays.toString(shift));

        // Copies of object arrays are shallow: both arrays point to the same objects
        StringBuilder[] original = {new StringBuilder("x"), new StringBuilder("y")};
        StringBuilder[] shallow = original.clone();
        shallow[0].append("!");                    // changes the shared object
        shallow[1] = new StringBuilder("new");     // replaces a slot in the copy only
        System.out.println("original after changing the copy: " + Arrays.toString(original));

        // clone() of a 2D array copies only the outer array
        int[][] grid = {{1, 2}, {3, 4}};
        int[][] outerOnly = grid.clone();
        int[][] deep = Arrays.stream(grid).map(int[]::clone).toArray(int[][]::new);
        outerOnly[0][0] = -1;
        System.out.println("grid after outerOnly[0][0] = -1: " + Arrays.deepToString(grid));
        deep[1][1] = -4;
        System.out.println("grid after deep[1][1] = -4:      " + Arrays.deepToString(grid));
    }
}

Output:

Output
clone:           [10, 20, 30, 40, 50]
copyOf:          [10, 20, 30, 40, 50]
copyOfRange 1-4: [20, 30, 40]
arraycopy:       [10, 20, 30, 40, 50]
shifted right:   [99, 1, 2, 3, 4]
original after changing the copy: [x!, y]
grid after outerOnly[0][0] = -1: [[-1, 2], [3, 4]]
grid after deep[1][1] = -4:      [[-1, 2], [3, 4]]
Ways to copy an array
MethodCreates the target?Use when
array.clone()Yes, same lengthA full copy
Arrays.copyOf(array, n)Yes, length n (shorter truncates, longer pads with defaults)A copy that grows or shrinks
Arrays.copyOfRange(array, from, to)Yes; to is excludedA slice
System.arraycopy(src, srcPos, dst, dstPos, n)No, copies into an existing arrayFilling part of an array, or moving elements within one array
  • System.arraycopy works correctly when source and target overlap: shifting {1, 2, 3, 4, 0} right by one gave {1, 1, 2, 3, 4} before index 0 was set to 99. A hand-written forward loop would have copied 1 into every slot. This is how ArrayList.add(index, element) makes room.
  • After shallow = original.clone(), both arrays point to the same StringBuilder objects. Appending through the copy changed original[0] to "x!", but replacing shallow[1] with a new object did not affect original[1].
  • A 2D array is an array of row arrays, so grid.clone() copies only the outer array, and the rows stay shared: setting outerOnly[0][0] changed grid. Cloning each row as well gives a real deep copy, and changing deep[1][1] left grid alone.

Two-dimensional and jagged arrays

The program fills a 3 by 4 grid with one value, then builds Pascal's triangle, in which each row is one element longer than the one before, so the rows cannot all have the same length.

Java
import java.util.Arrays;

public class MultiDim {

    public static void main(String[] args) {
        int[][] grid = new int[3][4];              // 3 rows of 4
        grid[1][2] = 7;
        for (int[] row : grid) {
            System.out.println(Arrays.toString(row));
        }

        // A 2D array is an array of arrays, so rows can differ in length
        int[][] triangle = new int[4][];
        for (int i = 0; i < triangle.length; i++) {
            triangle[i] = new int[i + 1];
            triangle[i][0] = 1;
            triangle[i][i] = 1;
            for (int j = 1; j < i; j++) {
                triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
            }
        }
        System.out.println(Arrays.deepToString(triangle));

        // Arrays.toString prints the inner arrays' addresses; deepToString prints contents
        boolean refs = Arrays.toString(grid).contains("[I@");
        System.out.println("Arrays.toString(grid) shows [I@...: " + refs);
    }
}

Output:

Output
[0, 0, 0, 0]
[0, 0, 7, 0]
[0, 0, 0, 0]
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
Arrays.toString(grid) shows [I@...: true

Java has no true 2D arrays. new int[3][4] creates an array of 3 references, each to its own int[4]. That is why rows can have different lengths, a jagged array, created by leaving the second size empty (new int[4][]) and filling in each row. It is also why Arrays.toString shows the rows as references, and Arrays.deepToString is needed to print their contents. Each row of Pascal's triangle is computed from the row above: every inner value is the sum of the two values above it.

The Arrays helper class

java.util.Arrays has static methods for the jobs arrays cannot do themselves: sorting, searching, filling, comparing and converting.

Java
import java.util.Arrays;
import java.util.List;

public class ArraysUtility {

    public static void main(String[] args) {
        int[] data = {42, 7, 19, 3, 25};

        int[] sorted = data.clone();
        Arrays.sort(sorted);
        System.out.println("sort:          " + Arrays.toString(sorted));
        System.out.println("binarySearch:  " + Arrays.binarySearch(sorted, 19));

        int[] filled = new int[5];
        Arrays.fill(filled, -1);
        System.out.println("fill:          " + Arrays.toString(filled));

        System.out.println("copyOfRange:   " + Arrays.toString(Arrays.copyOfRange(data, 1, 3)));
        System.out.println("copyOf longer: " + Arrays.toString(Arrays.copyOf(data, 7)));
        System.out.println("stream sum:    " + Arrays.stream(data).sum());
        System.out.println("max:           " + Arrays.stream(data).max().getAsInt());
        System.out.println("mismatch:      " + Arrays.mismatch(data, new int[] {42, 7, 0}));

        // Arrays.asList on an object array: a fixed-size list view
        String[] words = {"b", "a", "c"};
        List<String> view = Arrays.asList(words);
        view.set(0, "z");
        System.out.println("asList view writes through: " + Arrays.toString(words));

        // Arrays.asList on an int[] gives a list of ONE element: the array itself
        System.out.println("Arrays.asList(int[]).size(): " + Arrays.asList(data).size());
        List<Integer> boxed = Arrays.stream(data).boxed().toList();
        System.out.println("boxed list size:             " + boxed.size());
    }
}

Output:

Output
sort:          [3, 7, 19, 25, 42]
binarySearch:  2
fill:          [-1, -1, -1, -1, -1]
copyOfRange:   [7, 19]
copyOf longer: [42, 7, 19, 3, 25, 0, 0]
stream sum:    96
max:           42
mismatch:      2
asList view writes through: [z, a, c]
Arrays.asList(int[]).size(): 1
boxed list size:             5
  • sort works in place, so the program sorts a clone() to keep the original order. For primitives it uses a dual-pivot quicksort; for objects, a stable merge sort (TimSort), which keeps equal elements in their original order.
  • binarySearch found 19 at index 2 of the sorted array. On an unsorted array its result is undefined, not an error.
  • copyOf with a larger length padded with zeros; mismatch returned 2, the first index where the arrays differ, or -1 if they are equal.
  • Arrays.asList wraps an object array as a fixed-size list. Writes go through to the array, and add or remove throw UnsupportedOperationException.
  • Given an int[], Arrays.asList cannot box the elements, so it returns a list with one element: the array itself. Use Arrays.stream(data).boxed().toList().

How arrays grow: what ArrayList does

Since an array cannot grow, a growable list keeps a bigger array than it needs and, when that fills up, copies everything into a new one. This program implements that with the same rule ArrayList uses, growing by 50% each time, and counts the copying while adding 1,000,000 numbers.

Java
import java.util.Arrays;

public class GrowingArray {

    // A minimal growable int list: what ArrayList does inside
    static int[] data = new int[2];
    static int size;
    static int copies;
    static long copiedElements;

    static void add(int value) {
        if (size == data.length) {
            int newLength = data.length + (data.length >> 1);   // grow by 50%, like ArrayList
            copiedElements += size;
            copies++;
            data = Arrays.copyOf(data, Math.max(newLength, size + 1));
        }
        data[size++] = value;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000000; i++) {
            add(i);
        }
        System.out.println("elements added:   " + size);
        System.out.println("capacity now:     " + data.length);
        System.out.println("times copied:     " + copies);
        System.out.println("elements copied:  " + copiedElements);
        System.out.printf("copies per add:   %.2f%n", (double) copiedElements / size);
    }
}

Output:

Output
elements added:   1000000
capacity now:     1049869
times copied:     33
elements copied:  2099752
copies per add:   2.10

Growing by a fixed ratio means the array was copied only 33 times for a million additions, and each element was copied about twice on average. So adding is cheap on average ("amortized constant time"), even though an individual add that triggers a copy is slow. Growing by a fixed amount instead, say 10 slots at a time, would copy elements about 50,000 times per element on average. When you know the final size, pass it to the constructor (new ArrayList<>(n)) and no copying happens at all. The real ArrayList starts with 10 slots on the first add rather than 2.

Memory: int[] versus ArrayList

A list cannot hold primitives, so each number becomes an Integer object and the list stores a reference to it. The program measures the heap used by one million numbers both ways. The values start at 1,000 so they are outside the small range that Integer caches and shares.

Java
import java.util.ArrayList;
import java.util.List;

public class ArrayMemory {

    static long usedAfterGc() {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
        }
        return rt.totalMemory() - rt.freeMemory();
    }

    public static void main(String[] args) {
        int n = 1000000;

        long before = usedAfterGc();
        int[] primitives = new int[n];
        for (int i = 0; i < n; i++) {
            primitives[i] = i + 1000;             // values above the Integer cache (-128..127)
        }
        long arrayBytes = usedAfterGc() - before;

        before = usedAfterGc();
        List<Integer> boxed = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            boxed.add(i + 1000);
        }
        long listBytes = usedAfterGc() - before;

        System.out.printf("int[1,000,000]:            %,11d bytes (%.1f per element)%n",
                arrayBytes, (double) arrayBytes / n);
        System.out.printf("ArrayList<Integer> of 1M:  %,11d bytes (%.1f per element)%n",
                listBytes, (double) listBytes / n);
        System.out.println("still reachable: " + (primitives.length + boxed.size()));
    }
}

Output (JDK 21, 64-bit, run with -XX:+UseSerialGC so the measurement is stable):

Output
int[1,000,000]:              3,993,312 bytes (4.0 per element)
ArrayList<Integer> of 1M:   20,000,264 bytes (20.0 per element)
still reachable: 2000000

The int[] needs 4 bytes per number. The list needs 20: a 4-byte reference in the list's internal array plus a 16-byte Integer object (12 bytes of object header and 4 bytes of value). That is 5 times the memory, and reading the numbers means following a reference to a different place in memory for each one, which is slower too. For large amounts of numeric data, primitive arrays (or IntStream) are the better choice.

Traps that come from arrays being objects

Arrays predate generics and have some rules of their own. The program shows the five that cause the most surprises.

Java
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ArrayTraps {

    // new T[n] does not compile; reflection can create an array of a runtime type
    @SuppressWarnings("unchecked")
    static <T> T[] newArray(Class<T> type, int length) {
        return (T[]) Array.newInstance(type, length);
    }

    public static void main(String[] args) {
        // 1. Arrays are covariant: a String[] can be used as an Object[]...
        String[] strings = {"a", "b"};
        Object[] objects = strings;
        try {
            objects[0] = 42;                       // ...but storing an Integer fails at run time
        } catch (ArrayStoreException e) {
            System.out.println("ArrayStoreException: " + e.getMessage());
        }

        // 2. Arrays use identity for equals and hashCode
        Set<int[]> set = new HashSet<>();
        set.add(new int[] {1, 2});
        set.add(new int[] {1, 2});
        System.out.println("HashSet of two equal int[]: size " + set.size());
        System.out.println("Arrays.hashCode equal: "
                + (Arrays.hashCode(new int[] {1, 2}) == Arrays.hashCode(new int[] {1, 2})));

        // 3. Arrays.equals compares one level; nested arrays need deepEquals
        int[][] p = {{1}, {2}};
        int[][] q = {{1}, {2}};
        System.out.println("Arrays.equals(2D):     " + Arrays.equals(p, q));
        System.out.println("Arrays.deepEquals(2D): " + Arrays.deepEquals(p, q));

        // 4. Generic arrays
        String[] made = newArray(String.class, 3);
        System.out.println("Array.newInstance: " + made.getClass().getSimpleName()
                + " of length " + made.length);

        // 5. The size limit: an int index, and the heap
        try {
            int[] huge = new int[Integer.MAX_VALUE];
            System.out.println(huge.length);
        } catch (OutOfMemoryError e) {
            System.out.println("new int[Integer.MAX_VALUE]: " + e.getMessage());
        }
    }
}

Output:

Output
ArrayStoreException: java.lang.Integer
HashSet of two equal int[]: size 2
Arrays.hashCode equal: true
Arrays.equals(2D):     false
Arrays.deepEquals(2D): true
Array.newInstance: String[] of length 3
new int[Integer.MAX_VALUE]: Requested array size exceeds VM limit
  1. Covariance: a String[] is also an Object[], so the compiler accepts objects[0] = 42. The array still knows it holds strings, and the store fails at run time with ArrayStoreException. Generic lists do not have this problem, because List<String> is not a List<Object>.
  2. Identity: arrays do not override equals and hashCode, so a HashSet kept two arrays with the same contents. Do not use arrays as map keys or set elements; use a List or a record. Arrays.hashCode and Arrays.equals compute content-based values when you need them.
  3. Nesting: Arrays.equals compares the rows of a 2D array with ==, so it returned false; Arrays.deepEquals compares contents at every level.
  4. Generics: new T[n] does not compile, because the element type must be known at run time and generic types are erased. Array.newInstance(type, n) creates one from a Class object, as Collection.toArray(T[]) does internally.
  5. Size limit: indexes are int, so an array has at most about 2.1 billion elements, and the JVM reserves a few header words below that. new int[Integer.MAX_VALUE] fails immediately with "Requested array size exceeds VM limit"; slightly smaller arrays fail with "Java heap space" unless the heap is large enough (8 GB for that many ints).

Arrays or a List?

Choosing between an array and ArrayList
ArrayArrayList
SizeFixed at creationGrows automatically
PrimitivesStored directly: 4 bytes per intBoxed: about 20 bytes per Integer
Lengtharray.lengthlist.size()
Printing, equality, hashingNeed Arrays.toString, equals, hashCodeBuilt in
Type safetyChecked at run time (ArrayStoreException)Checked at compile time
Generic element typeNo new T[]Works with any type

Use arrays for fixed-size data, large amounts of primitive numbers and performance-critical code. Use a List almost everywhere else, because it is easier to use correctly. Arrays also underlie varargs, and list behavior is covered in ArrayList vs LinkedList.