Arrays
An array is a fixed-size, ordered container holding elements of a single type. Arrays are objects in Java, allocated on the heap, with a length field and zero-based indexing. They offer fast, constant-time access by index but cannot grow once created.
Declaration and Initialization
Declare an array with the element type and [], then allocate it with new or an array literal.
int[] scores = new int[5]; // 5 ints, all default to 0
int[] primes = {2, 3, 5, 7, 11}; // literal initialization
String[] names = new String[]{"Ada", "Linus"};
scores[0] = 90; // assign by index
System.out.println(scores.length); // 5
Output:
5
New numeric arrays default to 0, boolean arrays to false, and reference arrays to null. The size is fixed at creation; you cannot resize an array.
Note:
int[] ais the preferred declaration style overint a[]. Both compile, but the type-attached form reads more clearly.
Iterating Over Arrays
Use an indexed for loop when you need the position, or a for-each loop when you only need the values.
int[] data = {4, 8, 15, 16, 23, 42};
// indexed
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
// for-each
int sum = 0;
for (int value : data) {
sum += value;
}
System.out.println("\nSum: " + sum);
Output:
4 8 15 16 23 42
Sum: 108
Multidimensional Arrays
Java implements multidimensional arrays as arrays of arrays. This allows jagged arrays whose rows have different lengths.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // 6
// jagged array — rows of varying length
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{1, 2};
jagged[2] = new int[]{1, 2, 3};
for (int[] row : grid) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
Output:
6
1 2 3
4 5 6
The Arrays Utility Class
java.util.Arrays provides static helpers for common operations. Always import it: import java.util.Arrays;.
int[] nums = {5, 2, 8, 1, 9};
Arrays.sort(nums); // in-place sort -> [1, 2, 5, 8, 9]
int idx = Arrays.binarySearch(nums, 8); // 3 (array must be sorted)
int[] copy = Arrays.copyOf(nums, 7); // length 7, padded with 0
int[] slice = Arrays.copyOfRange(nums, 1, 4); // [2, 5, 8]
Arrays.fill(copy, 5, 7, -1); // set indices 5–6 to -1
System.out.println(Arrays.toString(nums)); // readable printing
System.out.println(Arrays.equals(nums, copy));
Output:
[1, 2, 5, 8, 9]
false
Tip: For multidimensional arrays use
Arrays.deepToString(grid)— plaintoStringonly prints object hashes for nested arrays.
Common Pitfalls
Accessing an index outside 0 to length - 1 throws ArrayIndexOutOfBoundsException at runtime.
int[] a = {10, 20, 30};
System.out.println(a[3]); // throws ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Other common mistakes:
- Using
array.length()(a method) instead ofarray.length(a field) — onlyStringhaslength(). - Assuming arrays grow — they don’t; use
ArrayListwhen you need a resizable collection. - Copying with
=only copies the reference, not the contents — both names point to the same array.
int[] original = {1, 2, 3};
int[] alias = original; // same array!
int[] real = original.clone(); // independent copy
alias[0] = 99;
System.out.println(original[0]); // 99 — original was modified
Best Practices
- Prefer for-each iteration to eliminate off-by-one and bounds errors.
- Use
Arrays.toString/deepToStringfor debugging instead of printing the raw reference. - Choose
ArrayListover arrays when the size is dynamic or unknown. - Validate indices derived from user input before accessing elements.
- Use
clone()orArrays.copyOffor a true copy; assignment only aliases.