The Plain Picture#
A row of numbered lockers, all the same size, side by side. Locker 0, locker 1, locker 2… You can go straight to any locker by its number, instantly. But the row has a fixed length — you can't add a locker at the end.
The Real Names#
An array is a fixed-length sequence of values of one type, stored side by side in memory.
Each value is an element; its position is its index, starting at 0.
arr.lengthis the number of elements (a field, no parentheses — unlikeString.length()).
Under the Hood#
Creating arrays#
int[] scores = new int[5]; // 5 ints, all 0
int[] marks = { 72, 95, 60, 88 }; // with initial values
String[] names = new String[2]; // 2 references, both null (no string yet)
System.out.println(Arrays.toString(scores)); // [0, 0, 0, 0, 0]Default values: 0 for numbers, false for boolean, '\u0000' for char, and null (= "refers to nothing") for object types:
System.out.println(
Arrays.toString(new boolean[2]) + " " + Arrays.toString(new String[2])
);
// [false, false] [null, null]Why index access is instant#
Because elements are side by side and all the same size, the address of element i is simple arithmetic
(How Computers Work Ch 7):
address of scores[i] = start address + i × 4 bytes (an int is 4 bytes)
index: 0 1 2 3 4
┌────────┬────────┬────────┬────────┬────────┐
│ 72 │ 95 │ 60 │ 88 │ 100 │
└────────┴────────┴────────┴────────┴────────┘
address: 0x1000 0x1004 0x1008 0x100C 0x1010One multiplication and one addition, regardless of the array's size — that's O(1) access (Big-O is taught in Big-O and Complexity). And because they're adjacent, walking through an array uses the CPU cache perfectly (How Computers Work Ch 6).
Out of bounds — a runtime error#
int[] s = new int[3];
System.out.println(s[3]);Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Oops.main(Oops.java:1)Valid indexes are 0 to length - 1. Java checks every access and stops the program instead of silently reading other memory
(which C would do — and which is a source of security holes).
The Arrays helper class#
import java.util.Arrays; // at the top of the file
int[] marks = { 72, 95, 60, 88 };
Arrays.sort(marks); // sorts in place, ascending
System.out.println(Arrays.toString(marks)); // [60, 72, 88, 95]
Arrays.fill(scores, -1); // set every element to -1
int[] copy = Arrays.copyOf(marks, marks.length); // a real, independent copy
int[] part = Arrays.copyOfRange(marks, 1, 3); // [72, 88] — from 1 up to (not including) 3
Arrays.equals(a, b); // same contents?(import makes a class from Java's standard library available by its short name.)
Arrays are references — aliasing#
int[] alias = marks; // NOT a copy — both names refer to the SAME array
alias[0] = 0;
System.out.println(Arrays.toString(marks)); // [0, 72, 88, 95] ← marks changed tooSame rule as pass-by-value in Chapter 7. To copy, use Arrays.copyOf or marks.clone().
2-D arrays — grids#
Many DSA problems are grids: a map of islands, a chessboard, a maze.
int[][] grid = new int[3][4]; // 3 rows, 4 columns, all 0
grid[1][2] = 7; // row 1, column 2
System.out.println(Arrays.deepToString(grid));
// [[0, 0, 0, 0], [0, 0, 7, 0], [0, 0, 0, 0]]
System.out.println(grid.length + " x " + grid[0].length); // 3 x 4 (rows x columns)A 2-D array is really an array of arrays: grid holds 3 references, each to a row array of 4 ints.
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
// visit grid[r][c]
}
}The four-neighbour pattern — used in almost every grid problem (flood fill, islands, shortest path):
int[][] dirs = {
{ -1, 0 },
{ 1, 0 },
{ 0, -1 },
{ 0, 1 },
}; // up, down, left, right
for (int[] d : dirs) {
int nr = r + d[0],
nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) {
// bounds check FIRST (short-circuit, Ch 3)
// visit neighbour grid[nr][nc]
}
}Counting with an array — a first DSA pattern#
How many times does each letter appear in "studybuddy"?
String word = "studybuddy";
int[] count = new int[26]; // one slot per letter a..z
for (int i = 0; i < word.length(); i++) {
count[word.charAt(i) - 'a']++; // 'a'→0, 'b'→1, ... (Ch 3)
}
// count['d' - 'a'] == 3, count['u' - 'a'] == 2, count['y' - 'a'] == 2You'll use this to solve "are two words anagrams?" and many more (Arrays and Hashing (coming soon)).
Gotchas
Arrays can't grow. When you need a list that grows, use
ArrayList(Collections, From the Inside) — which is secretly an array that gets replaced by a bigger one when it fills up.System.out.println(arr)prints something like[I@1b6d3586(the type and a hash code), not the contents. UseArrays.toString(arr).==on arrays compares references, not contents. UseArrays.equals.
Check yourself
5 questionsWhat are the valid indexes of an array of length n?
Show answerHide answer
0 to n - 1.
Why is reading arr[i] equally fast for any i?
Show answerHide answer
The address is computed directly as start + i × element size — one calculation regardless of i.
After int[] a = {1,2,3}; int[] b = a; b[1] = 9;, what is a? How do you make b an independent copy?
Show answerHide answer
[1, 9, 3] — they're the same array. Use int[] b = Arrays.copyOf(a, a.length); (or a.clone()).
For int[][] g = new int[5][8];, what are g.length and g[0].length?
Show answerHide answer
5 (rows) and 8 (columns).
Write the check that (nr, nc) is inside a grid with rows rows and cols columns.
Show answerHide answer
nr >= 0 && nr < rows && nc >= 0 && nc < cols.