What you'll learn
A single variable holds one value — but real programs handle many: a list of scores, the days of the week, pixels on a screen. An array stores a fixed-size sequence of values under one name, each reachable by its position.
By the end you'll be able to:
- Declare, create, and initialize arrays
- Access and modify elements by index, and use
length - Iterate arrays with both loop styles
- Pass arrays to methods and understand their reference behaviour
- Copy arrays safely and use the
Arraysutility class - Work with 2D and jagged arrays, and write common array algorithms
Creating arrays
An array has a fixed type and a fixed size set when you create it — it can never grow or shrink. You can create an empty array with new (every slot gets a default value: 0 for numbers, false for booleans, null for objects), or create and fill it at once with a literal:
int[] nums = new int[5]; // 5 slots, all default to 0
int[] primes = {2, 3, 5, 7, 11}; // create + fill in one step
String[] names = {"Sara", "Omar"};
System.out.println(nums[0]); // 0 (default value)
System.out.println(primes[2]); // 5
System.out.println(names.length); // 2int[] nums = {10, 20, 30, 40, 50} — length is 5, and the valid indexes run 0 to 4. The first element is nums[0], never nums[1].
Accessing elements & length
You read or change an element with square brackets and its index: nums[0] is the first, nums[nums.length - 1] is the last. The number of elements is always available as .length (a field, not a method — no parentheses).
int[] scores = {70, 80, 90};
scores[1] = 85; // modify the element at index 1
System.out.println(scores[1]); // 85
System.out.println(scores.length); // 3
System.out.println(scores[3]); // out of bounds!ArrayIndexOutOfBoundsException
nums[3] crashes at runtime. This is the #1 array error — always keep indexes between 0 and length - 1.Iterating over arrays
Arrays and loops are a perfect pair. Use a classic for when you need the index (or want to change elements), and the enhanced for when you just need to read each value:
int[] nums = {10, 20, 30, 40, 50};
for (int i = 0; i < nums.length; i++) { // classic for: has the index
System.out.println("Index " + i + " -> " + nums[i]);
}
int sum = 0;
for (int n : nums) { // enhanced for: just values
sum += n;
}
System.out.println("Sum = " + sum);Passing & returning arrays
Arrays are objects, so a variable holds a reference to the array, not the data itself. As you saw in Module 6, that means when you pass an array to a method, the method can change its contents and the caller sees those changes — they share the same array. Methods can also return arrays to hand back a whole collection of results.
Key idea
Copying arrays
Because arrays are references, int[] b = a; does not copy — it just makes b point at the same array as a. To get an independent copy, use Arrays.copyOf(), clone(), or System.arraycopy():
| Approach | What it does |
|---|---|
Arrays.copyOf(a, n) | New array of length n, copied from a (padded or trimmed) |
a.clone() | A quick shallow copy of the whole array |
System.arraycopy(...) | Fast, low-level copy of a range into another array |
Copies are shallow
The Arrays utility class
The java.util.Arrays class is a toolbox of static helpers that save you from writing common array code by hand:
| Method | What it does |
|---|---|
Arrays.toString(a) | A readable string like [1, 2, 3] (println shows gibberish otherwise) |
Arrays.sort(a) | Sorts the array ascending, in place |
Arrays.binarySearch(a, k) | Finds k's index — the array must be sorted first |
Arrays.fill(a, v) | Sets every element to v |
Arrays.equals(a, b) | true if both have the same elements in order |
import java.util.Arrays;
int[] nums = {5, 2, 9, 1, 7};
Arrays.sort(nums); // sorts in place
System.out.println(Arrays.toString(nums)); // [1, 2, 5, 7, 9]
int idx = Arrays.binarySearch(nums, 7); // needs a sorted array
System.out.println("Found 7 at index " + idx);
int[] first3 = Arrays.copyOf(nums, 3);
System.out.println(Arrays.toString(first3)); // [1, 2, 5]Tip
System.out.println(nums)) shows something like [I@1b6d3586 — the object's memory hash. Always wrap it in Arrays.toString() to see the values.2D & jagged arrays
An array can hold other arrays, giving you a grid. A 2D array is declared with two sets of brackets and accessed with two indexes — grid[row][col]:
A 2×3 grid: the first index is the row, the second is the column.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // row 1, col 2 -> 6
System.out.println(grid.length); // 2 (rows)
System.out.println(grid[0].length); // 3 (columns)
for (int[] row : grid) {
System.out.println(java.util.Arrays.toString(row));
}Note
Common array algorithms
Most array work boils down to a handful of patterns: summing, finding a max or min, searching, and reversing. Here's the "find the maximum" pattern — start by assuming the first element is biggest, then let the loop correct you:
int[] nums = {23, 8, 42, 15, 4, 16};
int max = nums[0]; // assume the first is biggest
for (int n : nums) {
if (n > max) {
max = n; // found a bigger one
}
}
System.out.println("Max = " + max);Tip
Recap & quick check
Key takeaways
- An array is a fixed-size, indexed sequence of one type; indexes run 0 to length - 1.
- Use .length (a field) for the size, and mind ArrayIndexOutOfBoundsException.
- Arrays are references: assigning or passing them shares the same data — copy to stay independent.
- Arrays.toString, sort, binarySearch, and copyOf handle common tasks for you.
- 2D arrays are arrays of arrays, accessed as grid[row][col].
Quick check
1. What is the valid index range for an array of length 5?
2. How do you get the number of elements in an array named data?
3. What happens with 'int[] b = a;' where a is an array?
4. Which method prints an array's contents readably?
5. How do you access the value in row 1, column 2 of a 2D array grid?
Congratulations — you've completed Phase 1! You can now store data, make decisions, repeat work, organise code into methods, and manage collections of values. Next you'll step into Phase 2 — Object-Oriented Java, starting with Module 8, where everything you know comes together into classes and objects.