Notifications

No notifications

/Phase 2

Arrays & Arrays Utility

Arrays — Fixed-Size Containers 📊

A Java array holds a fixed number of values of one type. Once allocated, its length never changes.

int[] nums = new int[5];           // {0, 0, 0, 0, 0}
int[] xs   = {10, 20, 30, 40};     // literal
String[] names = new String[3];     // {null, null, null}

nums[0] = 7; int x = nums[0]; int len = nums.length; // FIELD, not method

Iterating

for (int i = 0; i < xs.length; i++) System.out.println(xs[i]);
for (int v : xs) System.out.println(v);              // foreach

2D Arrays

int[][] grid = new int[3][4];                        // 3 rows × 4 cols
int[][] mat  = { {1,2,3}, {4,5,6} };
mat[1][2] = 99;

java.util.Arrays

import java.util.Arrays;

int[] a = {3, 1, 4, 1, 5}; Arrays.sort(a); // [1,1,3,4,5] int i = Arrays.binarySearch(a, 4); // 3 (must be sorted) int[] c = Arrays.copyOf(a, 8); // length 8 (zeros padded) int[] s = Arrays.copyOfRange(a, 1, 4); Arrays.fill(a, 0); // [0,0,0,0,0] String show = Arrays.toString(a); // "[0, 0, 0, 0, 0]" boolean eq = Arrays.equals(a, b);

For dynamic resize, jump to ArrayList (covered in Collections).

On this page

Detailed Theory

Declaration & Allocation

int[] a;                    // declare
a = new int[5];             // allocate (zero-initialised)

int[] b = new int[5]; // declare + allocate int[] c = {10, 20, 30}; // literal int[] d = new int[]{10, 20, 30}; // explicit form (needed in returns/args)

String[] words = new String[3]; // [null, null, null]

> Reference-type arrays default to null. Numeric arrays default to 0 (or 0.0). boolean[] defaults to false.

Length

int len = a.length;     // FIELD — no parentheses!

String uses length() (method), arrays use length (field). Easy to swap by mistake.

Indexing

Zero-based. Out-of-range access throws ArrayIndexOutOfBoundsException at runtime:

int[] a = {10, 20, 30};
a[3];   // throws ArrayIndexOutOfBoundsException
a[-1];  // also throws

Iteration Patterns

int[] a = {10, 20, 30};

// Index access for (int i = 0; i < a.length; i++) System.out.println(a[i]);

// Foreach (clearest) for (int x : a) System.out.println(x);

// Index + value (manual) for (int i = 0; i < a.length; i++) { System.out.printf("%d -> %d%n", i, a[i]); }

2D Arrays — Array of Arrays

Java has no true 2D arrays — they're arrays of arrays, which means rows can be different lengths (jagged):

int[][] mat = new int[3][4];        // 3×4 rectangular
mat[0][0] = 1;
int rows = mat.length;
int cols = mat[0].length;

int[][] jagged = { {1, 2}, {3, 4, 5}, {6} };

for (int[] row : jagged) { for (int v : row) System.out.print(v + " "); System.out.println(); }

Copying

int[] a = {1, 2, 3, 4, 5};

// Shallow copy (whole array, same length) int[] b = a.clone();

// Resize int[] bigger = Arrays.copyOf(a, 10); // pads with 0s int[] slice = Arrays.copyOfRange(a, 1, 4); // [2,3,4]

// Manual / partial copy int[] dst = new int[5]; System.arraycopy(a, 0, dst, 0, a.length);

> clone() is shallow. For String[][] you'd need to clone each row separately to deep-copy.

java.util.Arrays — The Toolbox

import java.util.Arrays;

int[] a = {3, 1, 4, 1, 5, 9, 2, 6};

Arrays.sort(a); // in-place, dual-pivot quicksort, O(n log n) Arrays.sort(a, 2, 5); // sort range [2..5)

int idx = Arrays.binarySearch(a, 4); // O(log n) — array MUST be sorted Arrays.fill(a, 0); // fill all with 0 Arrays.fill(a, 2, 5, -1); // fill range with -1

System.out.println(Arrays.toString(a)); // "[3, 1, 4, 1, 5]" System.out.println(Arrays.equals(a, b)); // element-wise equality

// 2D int[][] m = { {1,2}, {3,4} }; System.out.println(Arrays.deepToString(m)); // "[[1, 2], [3, 4]]" System.out.println(Arrays.deepEquals(m, n));

Sorting Objects

Integer[] nums = {3, 1, 4, 1, 5};
Arrays.sort(nums);                                    // natural order
Arrays.sort(nums, Comparator.reverseOrder());         // descending
Arrays.sort(strs, Comparator.comparingInt(String::length));   // by length

> Note: Arrays.sort on int[] (primitive) → quicksort. On Integer[] (object) → stable mergesort. Different guarantees.

Array → Stream → List

import java.util.Arrays;
import java.util.List;

int[] a = {1, 2, 3}; int sum = Arrays.stream(a).sum(); int max = Arrays.stream(a).max().getAsInt(); int[] doubled = Arrays.stream(a).map(x -> x * 2).toArray();

String[] names = {"Asha", "Bishan"}; List<String> list = Arrays.asList(names); // FIXED-SIZE view! List<String> mutable = new ArrayList<>(Arrays.asList(names)); // resizable copy

> ⚠️ Arrays.asList returns a fixed-size, backing-array-shared list. add/remove throw UnsupportedOperationException. Wrap in new ArrayList<>(...) if you need a real list.

Array vs ArrayList

int[] (array)ArrayList
SizeFixedResizable
TypePrimitive or referenceReference only (boxes)
MemoryCompactObject overhead per element
APIlength, indexingsize(), add, remove, indexOf
SpeedFastestSlightly slower (autoboxing)

Use arrays when size is known + speed matters. Use ArrayList for dynamic data — covered in Collections.

Common Patterns

Reverse in place

static void reverse(int[] a) {
    int i = 0, j = a.length - 1;
    while (i < j) {
        int t = a[i]; a[i] = a[j]; a[j] = t;
        i++; j--;
    }
}

Frequency count

int[] freq = new int[26];
for (char c : "hello".toCharArray()) freq[c - 'a']++;

Two-pointer sum

static int[] twoSumSorted(int[] a, int target) {
    int i = 0, j = a.length - 1;
    while (i < j) {
        int s = a[i] + a[j];
        if (s == target) return new int[]{i, j};
        if (s < target) i++; else j--;
    }
    return new int[]{-1, -1};
}

Common Mistakes

BugFix
a.length() for an arrayArrays use a.length (field). String uses length() (method)
Trying to grow an arrayAllocate a bigger one + copyOf, or switch to ArrayList
Modifying the result of Arrays.asListWrap in new ArrayList<>(...)
Arrays.sort then binarySearch on a different arrayBoth must operate on the same sorted array
a.clone() for 2D arrays expecting deep copyClone each row in a loop
== to compare arraysUse Arrays.equals or Arrays.deepEquals

Cheat-Sheet

NeedCode
New zeroed arraynew int[n]
Literal{1, 2, 3}
Lengtha.length (field)
2Dnew int[r][c] or { {1,2}, {3,4} }
SortArrays.sort(a)
Binary searchArrays.binarySearch(a, k) (sorted)
FillArrays.fill(a, val)
PrintArrays.toString(a), deepToString
CopyArrays.copyOf(a, len), copyOfRange(a, i, j)
EqualsArrays.equals(a, b)
Sum / maxArrays.stream(a).sum() / .max()
Array → Listnew ArrayList<>(Arrays.asList(arr))

You can now wield Java's fixed-size containers. Next: classes — your own types.