Arrays
What you'll learn:
- create an array, read its elements by index and change them;
- loop over an array, print it and sort it with
Arrays; - explain why
int[] b = adoes not copy an array, and compare arrays the right way; - work with a two-dimensional array and find the number of its rows and columns.
Picture a row of identical lockers in a changing room. Each locker has a number on its door, and you find the one you need by that number: "open locker 2". All the lockers are the same size, and the row cannot be made longer: it has as many lockers as were put there.
Programs often need a row like this. Say you need to keep the scores of three players. You could declare three variables: score1, score2 and score3. But a hundred players would need a hundred variables. And picking a player's score by their number does not work at all: the number here is part of a name, not a value you can compute.
For data like this Java has the array, a row of numbered cells under one name:
public class Main {
public static void main(String[] args) {
int[] scores = {90, 75, 60};
System.out.println(scores[0]); // 90
System.out.println(scores[2]); // 60
scores[1] = 80;
System.out.println(scores[1]); // 80
System.out.println(scores.length); // 3
}
}Let's walk through the program line by line:
int[] scores = {90, 75, 60};creates a row of three cells and puts three numbers into them.scores[0]reads the first cell. Numbering starts at zero, so it prints90.scores[2]is the third and last cell:60.scores[1] = 80;puts80into the second cell in place of75.scores.lengthis how many cells the array has:3.
What an array is
An array is a row of cells of one type under one name. A cell of an array is called an element, and its number is its index. The index goes in square brackets after the name: scores[1].
The array type is written with brackets too: int[] reads as "array of int". An array can be built from elements of any type: double[], boolean[], String[]. You have already seen String[] args in the header of main: it is an array of strings.
Each element behaves like a separate variable of its type:
scores[1]inside an expression reads the element's value;scores[1] = 80;puts a new value into the element, and the old one is gone;- an element of
int[]takes only anint, like an ordinaryintvariable.
Two ways to create an array
Values in braces
The form int[] scores = {90, 75, 60}; lists the elements right away. Java counts the length itself, from the number of values. You use this form when the values are known in advance.
A row of a given length with new
When the values will come later, you create the array with the word new and give the length in square brackets. Every element of such an array gets a default value, the same as a field does: zeros for numbers, false for boolean and null for String.
int[] counts = new int[4];
counts[0] = 7;
System.out.println(counts[0]); // 7
System.out.println(counts[3]); // 0
System.out.println(counts.length); // 4Let's go line by line:
new int[4]creates a row of four cells, each holding0.counts[0] = 7;puts7into the first cell.counts[3]is the last cell; nothing was put there, so it holds0.counts.lengthprints4.
Indices from zero to length - 1
An array of three elements has the indices 0, 1 and 2. The first element is always scores[0], and the last is scores[scores.length - 1]. Any expression of type int can go in the square brackets, including a variable or a calculation.
Here the locker picture is off. In a changing room the numbers usually start at one, while in Java they start at zero. It helps to read an index as "how many lockers to step from the start of the row": the first one stands right at the start, a step of zero.
An array's length is set when it is created and never changes after that. You cannot add a fourth element to an array of three: you need a new, longer array. The length is written without parentheses: scores.length, and scores.length() does not compile.
Common mistake
You wanted the last element but wrote an index equal to the length:
int[] scores = {90, 75, 60};
System.out.println(scores[scores.length]); // ✗Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3The program compiles: the compiler does not track which number ends up in an index. The JVM finds the error only at run time. An array of length 3 has no cell with index 3, so the JVM throws an ArrayIndexOutOfBoundsException and stops the program. The last element is scores[scores.length - 1].
Key points
- An array is a row of elements of one type under one name:
int[] scores = {90, 75, 60};. - Indices run from
0tolength - 1: the first element isscores[0], the last isscores[scores.length - 1]. new int[4]creates an array of four zeros, and an array's length never changes after it is created.- An index past the end of the array compiles, but throws an
ArrayIndexOutOfBoundsExceptionat run time.