Arrays in Java
BeginnerDeclare, initialise, and traverse arrays. Explore multi-dimensional arrays, the Arrays utility class, and when to prefer ArrayList.
Overview
Arrays are the simplest and most memory-efficient way to store a fixed-size sequence of values in Java. An array stores elements in contiguous memory, enabling O(1) random access by index. The length is fixed at creation time — once allocated, it cannot grow. For dynamic sizing, use ArrayList. Arrays form the backbone of many DSA patterns (two-pointer, sliding window, prefix sum) and understanding them deeply is essential for coding interviews.
Declaration, Initialisation & Basics
You declare an array with type[], allocate it with new type[size], and access elements with zero-based indices. Accessing an out-of-bounds index throws ArrayIndexOutOfBoundsException at runtime. The length property (not a method) gives the size.
Array initialisers let you declare and populate in one line. For primitive arrays, elements default to 0/false. For object arrays, elements default to null.
import java.util.Arrays;
public class ArrayBasics {
public static void main(String[] args) {
// Declaration and allocation
int[] scores = new int[5]; // [0, 0, 0, 0, 0]
scores[0] = 95;
scores[4] = 87;
System.out.println(scores.length); // 5
// Array initialiser — size inferred
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
// Enhanced for-each
for (String day : days) System.out.print(day + " ");
System.out.println();
// Arrays utility methods
int[] nums = {5, 2, 8, 1, 9, 3};
Arrays.sort(nums); // in-place sort
System.out.println(Arrays.toString(nums)); // [1, 2, 3, 5, 8, 9]
int idx = Arrays.binarySearch(nums, 5); // works only on sorted array
System.out.println("Index of 5: " + idx);
int[] copy = Arrays.copyOf(nums, 4); // first 4 elements
System.out.println(Arrays.toString(copy)); // [1, 2, 3, 5]
int[] range = Arrays.copyOfRange(nums, 2, 5); // indices 2..4
System.out.println(Arrays.toString(range)); // [3, 5, 8]
int[] filled = new int[4];
Arrays.fill(filled, 7);
System.out.println(Arrays.toString(filled)); // [7, 7, 7, 7]
}
}2D & Multi-Dimensional Arrays
A 2D array in Java is an array of arrays. Each row is a separate heap object, which means rows can have different lengths (jagged arrays). This differs from C where memory is truly contiguous.
System.arraycopy is the fastest way to bulk-copy array regions — it calls native code under the hood. Arrays.copyOfRange is cleaner for slicing.
import java.util.Arrays;
public class TwoDArray {
public static void main(String[] args) {
// 3×3 matrix
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Traverse rows and columns
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
// Access element: O(1)
System.out.println(matrix[1][2]); // 6
// Jagged array — rows of different lengths
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{2, 3};
jagged[2] = new int[]{4, 5, 6};
// Matrix dimensions
System.out.println(matrix.length); // 3 rows
System.out.println(matrix[0].length); // 3 columns
// System.arraycopy: fast native bulk copy
int[] src = {1, 2, 3, 4, 5};
int[] dst = new int[5];
System.arraycopy(src, 1, dst, 0, 3); // copy src[1..3] to dst[0..2]
System.out.println(Arrays.toString(dst)); // [2, 3, 4, 0, 0]
}
}Common Array Patterns
Arrays drive the most important algorithm patterns in interviews:
Prefix Sum — precompute running totals so any range sum query is O(1) after O(n) setup. Two Pointer — left/right pointers moving toward each other; reduces O(n²) to O(n) for pair-sum problems. Sliding Window — maintain a window of size k as you slide across the array; avoid recomputing the whole window each step.
Always check the problem constraints: if array is sorted, binary search beats linear scan.
public class ArrayPatterns {
// Prefix sum: preprocess in O(n), then answer range queries in O(1)
public static int[] buildPrefix(int[] a) {
int[] p = new int[a.length + 1];
for (int i = 0; i < a.length; i++) p[i + 1] = p[i] + a[i];
return p;
}
public static int rangeSum(int[] prefix, int l, int r) {
return prefix[r + 1] - prefix[l]; // sum of a[l..r] inclusive
}
// Two pointer: find pair summing to target in sorted array — O(n)
public static int[] twoSum(int[] sorted, int target) {
int lo = 0, hi = sorted.length - 1;
while (lo < hi) {
int s = sorted[lo] + sorted[hi];
if (s == target) return new int[]{lo, hi};
else if (s < target) lo++;
else hi--;
}
return new int[]{-1, -1}; // not found
}
// Sliding window: max sum subarray of size k — O(n)
public static int maxWindowSum(int[] a, int k) {
int window = 0;
for (int i = 0; i < k; i++) window += a[i];
int max = window;
for (int i = k; i < a.length; i++) {
window += a[i] - a[i - k];
max = Math.max(max, window);
}
return max;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
int[] p = buildPrefix(arr);
System.out.println(rangeSum(p, 2, 5)); // 4+1+5+9 = 19
int[] sorted = {1, 3, 5, 7, 9};
System.out.println(java.util.Arrays.toString(twoSum(sorted, 10))); // [1,3]
System.out.println(maxWindowSum(arr, 3)); // 17 (9+2+6)
}
}Key Points to Remember
- Array length is fixed at creation; use ArrayList for dynamic sizing
- Elements default to 0/false (primitives) or null (objects) — no explicit init needed
- Arrays.sort() uses dual-pivot quicksort for primitives (O(n log n)) and TimSort for objects
- Arrays.binarySearch() only works correctly on a pre-sorted array
- System.arraycopy() is the fastest bulk-copy — it calls native code
- Prefix sum enables O(1) range queries; two-pointer reduces pair-sum from O(n²) to O(n)
Practice Arrays in Java in the Playground
Run and modify code directly in your browser - no setup needed.
Interview Questions
Sign in to ask AriaWhat is the difference between an array and an ArrayList in Java?
Find the maximum subarray sum (Kadane's Algorithm)
How would you rotate an array by k positions in O(1) space?
Find all pairs in an array that sum to a target value
What exception is thrown for an out-of-bounds array access?
Ask Aria about Arrays in Java
Your personal AI tutor — ask anything about this concept