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 iia[500000]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
does for you.ArrayList - An array is an object. A variable such as
holds a reference to it, so assigning or passing an array never copies its elements.int[] a - Primitive arrays store the values themselves, not references to objects, which makes
several times smaller than a list ofint[] .Integer
| Code | Result |
|---|---|
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 |
New elements always get a default value: 0'\u0000'charfalsebooleannull
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.
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:
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
, a field, not a method; for strings it isarray.length and for listslength() .size() - Valid indexes are 0 to
. Index 5 in a 5-element array throwslength - 1 , whose message names both the index and the length.ArrayIndexOutOfBoundsException - Printing an array directly calls
, which gives the type code and a hash such asObject.toString ([I@1b6d3586 means "array of int"). To see the elements, use[I .Arrays.toString copied the reference, so changingalias = primes changedalias[0] too.primes made a separate array, which kept the old values.Arrays.copyOf isa == b for two arrays with the same contents, becausefalse compares references.== compares the elements.Arrays.equals
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[]
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:
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]]
| Method | Creates the target? | Use when |
|---|---|---|
array.clone() | Yes, same length | A full copy |
Arrays.copyOf(array, n) | Yes, length n | A copy that grows or shrinks |
Arrays.copyOfRange(array, from, to) | Yes; to | A slice |
System.arraycopy(src, srcPos, dst, dstPos, n) | No, copies into an existing array | Filling part of an array, or moving elements within one array |
works correctly when source and target overlap: shiftingSystem.arraycopy right by one gave{1, 2, 3, 4, 0} before index 0 was set to 99. A hand-written forward loop would have copied 1 into every slot. This is how{1, 1, 2, 3, 4} makes room.ArrayList.add(index, element)- After
, both arrays point to the sameshallow = original.clone() objects. Appending through the copy changedStringBuilder to "x!", but replacingoriginal[0] with a new object did not affectshallow[1] .original[1] - A 2D array is an array of row arrays, so
copies only the outer array, and the rows stay shared: settinggrid.clone() changedouterOnly[0][0] . Cloning each row as well gives a real deep copy, and changinggrid leftdeep[1][1] alone.grid
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.
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:
[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]int[4]new int[4][]Arrays.toStringArrays.deepToString
The Arrays helper class
java.util.Arrays
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:
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
works in place, so the program sorts asort 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.clone() found 19 at index 2 of the sorted array. On an unsorted array its result is undefined, not an error.binarySearch with a larger length padded with zeros;copyOf returned 2, the first index where the arrays differ, or -1 if they are equal.mismatch wraps an object array as a fixed-size list. Writes go through to the array, andArrays.asList oradd throwremove .UnsupportedOperationException- Given an
,int[] cannot box the elements, so it returns a list with one element: the array itself. UseArrays.asList .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
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:
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)ArrayList
Memory: int[] versus ArrayList
A list cannot hold primitives, so each number becomes an IntegerInteger
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
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[]IntegerIntStream
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.
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:
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
- Covariance: a
is also anString[] , so the compiler acceptsObject[] . The array still knows it holds strings, and the store fails at run time withobjects[0] = 42 . Generic lists do not have this problem, becauseArrayStoreException is not aList<String> .List<Object> - Identity: arrays do not override
andequals , so ahashCode kept two arrays with the same contents. Do not use arrays as map keys or set elements; use aHashSet or a record.List andArrays.hashCode compute content-based values when you need them.Arrays.equals - Nesting:
compares the rows of a 2D array withArrays.equals , so it returned== ;false compares contents at every level.Arrays.deepEquals - Generics:
does not compile, because the element type must be known at run time and generic types are erased.new T[n] creates one from aArray.newInstance(type, n) object, asClass does internally.Collection.toArray(T[]) - Size limit: indexes are
, so an array has at most about 2.1 billion elements, and the JVM reserves a few header words below that.int 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 manynew int[Integer.MAX_VALUE] s).int
Arrays or a List?
| Array | ArrayList | |
|---|---|---|
| Size | Fixed at creation | Grows automatically |
| Primitives | Stored directly: 4 bytes per int | Boxed: about 20 bytes per Integer |
| Length | array.length | list.size() |
| Printing, equality, hashing | Need Arrays.toStringequalshashCode | Built in |
| Type safety | Checked at run time (ArrayStoreException | Checked at compile time |
| Generic element type | No new T[] | Works with any type |
Use arrays for fixed-size data, large amounts of primitive numbers and performance-critical code. Use a List