An array holds a fixed number of values of the same type.
Java
int[] marks = new int[5]; // five zeros
int[] scores = {88, 74, 91, 65}; // declare and fill
System.out.println(scores[0]); // 88 — indexes start at 0
System.out.println(scores.length); // 4 — a field, not a method
scores[1] = 80; // modifylength has no parentheses (unlike String.length()) — a small
inconsistency that catches everyone once.
Iterating
Java
for (int i = 0; i < scores.length; i++) {
System.out.println(i + ": " + scores[i]);
}
for (int s : scores) {
System.out.println(s);
}Arrays are fixed-size
You cannot grow an array. If you need to add and remove items, use
ArrayList (covered in the Collections chapter).
The Arrays utility class
Java
import java.util.Arrays;
int[] a = {5, 2, 9, 1};
Arrays.sort(a); // [1, 2, 5, 9]
System.out.println(Arrays.toString(a)); // "[1, 2, 5, 9]"
int idx = Arrays.binarySearch(a, 5); // 2 (array must be sorted)
int[] copy = Arrays.copyOf(a, 6); // longer copy, padded with 0
int[] part = Arrays.copyOfRange(a, 1, 3); // [2, 5]
Arrays.fill(a, 0); // all zerosSystem.out.println(array) prints something like [I@6d06d69c — the
type and hash, not the contents. Always use Arrays.toString().
2D arrays
Java
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
};
System.out.println(grid[1][2]); // 6
System.out.println(grid.length); // 2 — rows
System.out.println(grid[0].length); // 3 — columns in row 0
for (int[] row : grid) {
System.out.println(Arrays.toString(row));
}For 2D arrays, Arrays.deepToString(grid) prints the whole structure.
Common exception
Java
int[] a = new int[3];
a[3] = 10; // ArrayIndexOutOfBoundsException — valid indexes are 0,1,2