Arrays are the low-level building block under most collections, and appear in main(String[] args), varargs and performance-sensitive code.
An array is a fixed-size, ordered block of elements of one type. Create one with a size or with initial values:
int[] scores = new int[5]; // five zeros
String[] names = {"Ana", "Bo", "Cy"};Indexes start at 0, and the last valid index is length - 1. Note that length is a field, not a method: names.length. Accessing an index outside the range throws ArrayIndexOutOfBoundsException — Java always checks bounds.
New arrays are filled with default values: 0 for numbers, false for booleans, null for references.
An array variable holds a reference. Assigning int[] b = a; makes both names point at the same array, so changing b[0] changes a[0]. To copy, use Arrays.copyOf(a, a.length) or a.clone().
The java.util.Arrays class has the helpers you'll use constantly:
Arrays.toString(arr)— printing an array directly shows something like[I@1b6d3586, which is useless.Arrays.sort(arr)— sorts in place.Arrays.fill(arr, value)andArrays.equals(a, b)— the latter compares contents, unlike==.
Multi-dimensional arrays are arrays of arrays: int[][] grid = new int[3][4]; and grid[row][col].
Because arrays can't grow, application code usually prefers ArrayList, which you'll meet in the collections module. Reach for arrays for fixed-size data, primitives in hot loops, and APIs that require them.
Example
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
int[] nums = {5, 3, 9, 1};
int[] alias = nums; // same array, not a copy
int[] copy = Arrays.copyOf(nums, nums.length);
Arrays.sort(nums);
System.out.println(Arrays.toString(alias)); // [1, 3, 5, 9]
System.out.println(Arrays.toString(copy)); // [5, 3, 9, 1]
int max = Integer.MIN_VALUE;
for (int n : copy) max = Math.max(max, n);
System.out.println(max + " of " + copy.length); // 9 of 4
int[][] grid = new int[2][3];
grid[1][2] = 7;
System.out.println(Arrays.deepToString(grid)); // [[0, 0, 0], [0, 0, 7]]
}
}Remember
- Indexes run from 0 to
length - 1;lengthis a field - Array variables are references — assignment shares,
copyOfcopies - Use
Arrays.toString,sort,equalsinstead of hand-written loops
Watch out for
- Printing an array with
println(arr)and getting[I@6d06d69cinstead of its contents.