Lesson 6 of 23
In progress
Arrays
Create fixed-size arrays, index them safely, loop with length, and know when an ArrayList is the better choice.
An array holds a fixed number of values of one type, each reachable by index. It is the foundation the collection classes are built on, and it is still the right choice when the size is known and fixed.
What you will learn
- Create arrays with
newand with literals. - Read and write elements without going out of bounds.
- Copy, sort and search, and know when to switch to a list.
Creating arrays
public class ArraysDemo {
public static void main(String[] args) {
int[] scores = new int[5]; // five zeros
String[] names = new String[3]; // three nulls
int[] values = {4, 8, 15, 16, 23}; // literal
scores[0] = 91;
scores[1] = 78;
System.out.println(values.length); // 5
System.out.println(scores[0]); // 91
System.out.println(names[0]); // null
}
}
The length is fixed at creation and stored in the length field. There is no add and no way to grow: a "larger" array is a new array with the old values copied in.
Elements are initialised to the type’s default: 0 for numbers, false for booleans, null for objects. That is why names[0] is null rather than a compile error.
int[] scores and int scores[] both compile; the first is the convention, because the type is "array of int" rather than "int, and also an array".
Indexing and bounds
int[] values = {10, 20, 30};
System.out.println(values[2]); // 30
System.out.println(values[3]); // throws
Valid indexes run from 0 to length - 1. Java checks every access at runtime and throws ArrayIndexOutOfBoundsException rather than reading adjacent memory — a safety property that costs a small check per access.
The exception message includes the index and the length, which is enough to spot the usual off-by-one.
Negative indexes throw the same exception. There is no Python-style indexing from the end.
Looping
int[] values = {4, 8, 15, 16, 23, 42};
int sum = 0;
for (int value : values) {
sum += value;
}
System.out.println("sum: " + sum);
for (int i = 0; i < values.length; i++) {
if (values[i] % 2 == 0) {
System.out.println("even at " + i + ": " + values[i]);
}
}
The enhanced loop is for reading. The counting loop is for when the index matters, or when you need to write.
Writing through the enhanced variable does not work:
for (int value : values) {
value = value * 2; // changes the local copy only
}
To double every element, use the index:
for (int i = 0; i < values.length; i++) {
values[i] *= 2;
}
Arrays of objects
String[] names = {"Ana", "Ravi", "Meera"};
String[] copy = names.clone();
names[0] = "Ananya";
System.out.println(copy[0]); // Ana
clone copies the array, so reassigning an element in one does not affect the other. For an array of objects, the copy holds the same references: changing an object’s field through one array is visible through the other. That is a shallow copy, and it is the same behaviour as Arrays.copyOf.
Useful helpers
import java.util.Arrays;
int[] numbers = {5, 2, 9, 1};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 9]
int index = Arrays.binarySearch(numbers, 5);
System.out.println(index); // 2
int[] bigger = Arrays.copyOf(numbers, 6);
System.out.println(Arrays.toString(bigger)); // [1, 2, 5, 9, 0, 0]
Arrays.toString is the fastest way to see an array’s contents; printing the array directly gives something like [I@1b6d3586, which is the type and identity hash.
binarySearch requires a sorted array and returns a negative value when the element is absent, encoding the insertion point. copyOf grows by filling with defaults.
Two-dimensional arrays
int[][] grid = new int[3][4];
grid[1][2] = 7;
int[][] known = {
{1, 2, 3},
{4, 5, 6}
};
for (int[] row : known) {
for (int cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
A 2D array is an array of arrays, so rows can have different lengths. That is occasionally useful for triangular data and usually a source of confusion; if the shape is irregular, a list of lists is clearer.
Arrays versus ArrayList
Arrays are fixed-size, fast and compact. ArrayList grows, has helpful methods, and works with generics.
Use an array when:
- The size is known before creation.
- You need primitive storage without boxing.
- You are working with an API that requires one.
Use an ArrayList when items are added and removed at runtime, which is most application code. Converting between the two is easy: list.toArray(new String[0]) and Arrays.asList(array).
Passing arrays to methods
Arrays are objects, so a method receives a reference:
static void fill(int[] target, int value) {
Arrays.fill(target, value);
}
Calling fill(scores, 0) changes the caller’s array. That is convenient and it means a method can modify its argument unexpectedly; document it, or return a new array instead.
Comparing arrays with ==. It compares references, so two arrays with identical contents are not equal. Use Arrays.equals(a, b) for one dimension and Arrays.deepEquals for nested arrays.
Create an array of five prices in paise, double every price, then print the total in rupees and the most expensive item’s price.
Show solution
import java.util.Arrays; public class Prices { public static void main(String[] args) { long[] prices = {4500L, 32000L, 120000L, 15000L, 9900L}; for (int i = 0; i < prices.length; i++) { prices[i] *= 2; } long total = 0; long max = prices[0]; for (long price : prices) { total += price; if (price > max) { max = price; } } System.out.println(Arrays.toString(prices)); System.out.println("total rupees: " + total / 100.0); System.out.println("max rupees: " + max / 100.0); } } Doubling needs the index loop, because the enhanced variable is a copy. The second loop only reads, so the enhanced form is appropriate, and both total and max stay in long until the display conversion.
Recap
- Arrays are fixed-size, zero-indexed, and throw on an out-of-bounds access.
- Use
Arrays.toString,sort,copyOfandequalsrather than writing them. - Prefer
ArrayListwhen the size changes; use an array when it does not.
Module 3 turns to methods and objects: giving names to behaviour and state to your own types.
Can I resize an array?
Why does printing an array show gibberish?
Progress is saved in this browser only. No account, no email.