Arrays in Java
Learn Java arrays — single and multi-dimensional arrays, array operations, sorting, searching, and the Arrays utility class.
An array is a fixed-size, ordered container of elements of the same type. Arrays are the most fundamental data structure in Java — they underpin collections, sorting algorithms, and matrix operations. Knowing how they work at this level makes everything built on top of them easier to understand. All Java arrays are zero-indexed — the first element is at index 0.
Declaring and Creating Arrays
There are two ways to create an array: declare the size (and let Java fill with defaults), or declare with values inline. Use the second form whenever the values are known up front — it is less error-prone and more readable.
// Declaration + creation — elements initialised to default values
int[] scores = new int[5]; // 5 ints, all initialised to 0
String[] names = new String[3]; // 3 Strings, all null
// Declaration + initialisation in one step (preferred when values are known)
int[] primes = {2, 3, 5, 7, 11};
double[] temps = {36.6, 37.1, 36.9, 38.2};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
// Alternative syntax (less common)
int[] arr = new int[]{10, 20, 30};
Default values when you create without initialisation:
int,long,byte,short→0double,float→0.0boolean→falsechar→' '- Object references (String, etc.) →
null
Accessing Elements
Array elements are accessed by their zero-based index. Accessing an index outside 0 to length - 1 throws ArrayIndexOutOfBoundsException at runtime — one of the most common array bugs in Java.
int[] nums = {10, 20, 30, 40, 50};
System.out.println(nums[0]); // 10 — first element
System.out.println(nums[4]); // 50 — last element
System.out.println(nums.length); // 5 — number of elements
// Modify an element
nums[2] = 99;
System.out.println(nums[2]); // 99
// Last element by index — avoids hardcoding the length
System.out.println(nums[nums.length - 1]); // 50
nums[5] would throw ArrayIndexOutOfBoundsException — there is no index 5.
Iterating Arrays
Choose the right loop for the job: index-based for when you need the position, enhanced for when you only need the value. Mixing them up is a common beginner habit that leads to unnecessarily complex code.
int[] scores = {85, 92, 78, 95, 88};
// Index-based for — use when you need the index
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + i + ": " + scores[i]);
}
// Enhanced for — cleaner when you just need values
for (int score : scores) {
System.out.print(score + " ");
}
// 85 92 78 95 88
// Aggregate — sum and average
int total = 0;
for (int score : scores) total += score;
double avg = (double) total / scores.length;
System.out.printf("Average: %.1f%n", avg); // 87.6
Common Array Operations
The java.util.Arrays class provides ready-made utilities for the most common array tasks — sorting, searching, copying, and comparing. Always import it rather than reimplementing these from scratch.
import java.util.Arrays;
int[] arr = {64, 25, 12, 22, 11};
// Sorting — in-place, uses dual-pivot quicksort for primitives
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [11, 12, 22, 25, 64]
// Binary search — array MUST be sorted first, or results are undefined
int idx = Arrays.binarySearch(arr, 22);
System.out.println("22 at index: " + idx); // 2
// Fill with a value
int[] zeros = new int[5];
Arrays.fill(zeros, 7);
System.out.println(Arrays.toString(zeros)); // [7, 7, 7, 7, 7]
// Copy — creates a new array, does not affect the original
int[] copy = Arrays.copyOf(arr, arr.length); // full copy
int[] slice = Arrays.copyOfRange(arr, 1, 4); // [12, 22, 25]
// Compare — element-by-element equality
System.out.println(Arrays.equals(arr, copy)); // true
Finding Min and Max
Scanning for the minimum and maximum in a single pass is a fundamental pattern. Track both values in the same loop to avoid iterating the array twice.
int[] nums = {4, 2, 9, 7, 1, 5};
int min = nums[0], max = nums[0]; // start with first element as initial guess
for (int n : nums) {
if (n < min) min = n;
if (n > max) max = n;
}
System.out.println("Min: " + min + ", Max: " + max); // Min: 1, Max: 9
Reversing an Array
The two-pointer technique reverses in place without extra memory: start pointers at both ends and swap toward the middle until they meet.
int[] arr = {1, 2, 3, 4, 5};
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left]; // swap arr[left] and arr[right]
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
Linear Search
Linear search scans every element until it finds the target. It works on any array — sorted or not — and is the right choice when the array is small or unsorted. For large sorted arrays, use Arrays.binarySearch instead.
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i; // return index on first match
}
return -1; // convention: -1 means not found
}
int[] nums = {4, 2, 9, 7, 1};
System.out.println(linearSearch(nums, 7)); // 3
System.out.println(linearSearch(nums, 5)); // -1
Multi-Dimensional Arrays
2D Arrays
A 2D array is an array of arrays — think of it as a grid or matrix. This structure naturally models boards, images, spreadsheets, and any data with rows and columns.
// 3 rows, 4 columns
int[][] grid = new int[3][4];
// Initialise with values
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[1][2]); // 6 — row 1, column 2
System.out.println(matrix.length); // 3 — number of rows
System.out.println(matrix[0].length); // 3 — number of columns in row 0
Iterating a 2D Array
Nested loops map naturally onto the two dimensions: the outer loop walks rows, the inner loop walks columns within each row.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.printf("%3d", matrix[row][col]);
}
System.out.println();
}
// 1 2 3
// 4 5 6
// 7 8 9
Or with enhanced for:
for (int[] row : matrix) {
for (int val : row) {
System.out.printf("%3d", val);
}
System.out.println();
}
Jagged Arrays
Java 2D arrays do not have to be rectangular — each row can have a different length. This is useful for representing triangular data structures like Pascal’s triangle or adjacency lists.
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{2, 3};
jagged[2] = new int[]{4, 5, 6};
for (int[] row : jagged) {
System.out.println(Arrays.toString(row));
}
// [1]
// [2, 3]
// [4, 5, 6]
3D Arrays
A 3D array adds a third dimension — think layers of 2D grids. They are less common but appear in 3D graphics, scientific computing, and volumetric data.
int[][][] cube = new int[2][3][4]; // 2 layers, 3 rows, 4 columns
// Access using three indices: [layer][row][column]
cube[0][1][2] = 42;
System.out.println(cube[0][1][2]); // 42
Projects
Student Marks System
import java.util.Arrays;
import java.util.Scanner;
public class StudentMarks {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number of students: ");
int n = sc.nextInt();
String[] names = new String[n];
int[] marks = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Name: ");
names[i] = sc.next();
System.out.print("Marks: ");
marks[i] = sc.nextInt();
}
// Single pass to find top scorer and compute total
int maxMark = marks[0];
int maxIdx = 0;
int total = 0;
for (int i = 0; i < n; i++) {
total += marks[i];
if (marks[i] > maxMark) { maxMark = marks[i]; maxIdx = i; }
}
System.out.println("\n--- Report ---");
System.out.printf("Class average: %.1f%n", (double) total / n);
System.out.printf("Top scorer: %s (%d)%n", names[maxIdx], maxMark);
// Selection sort — sorts both arrays in parallel to keep names aligned with marks
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (marks[j] < marks[minIdx]) minIdx = j;
}
int tmpM = marks[i]; marks[i] = marks[minIdx]; marks[minIdx] = tmpM;
String tmpN = names[i]; names[i] = names[minIdx]; names[minIdx] = tmpN;
}
System.out.println("\nRanking (low to high):");
for (int i = 0; i < n; i++) {
System.out.printf("%d. %s — %d%n", i + 1, names[i], marks[i]);
}
sc.close();
}
}
Matrix Addition
public class MatrixAdd {
public static int[][] add(int[][] a, int[][] b) {
int rows = a.length, cols = a[0].length;
int[][] result = new int[rows][cols];
// Element-wise addition: result[i][j] = a[i][j] + b[i][j]
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result[i][j] = a[i][j] + b[i][j];
return result;
}
public static void print(int[][] m) {
for (int[] row : m) {
for (int val : row) System.out.printf("%4d", val);
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{7, 8, 9}, {1, 2, 3}};
System.out.println("A + B =");
print(add(a, b));
// 8 10 12
// 5 7 9
}
}