Array Creation and Access

An array keeps several values of one type under a single name, and each value is reached by its position. The examples below follow a five-car train and its count of empty seats in each car.
Creating an array with new
int[] emptySeats = new int[5];
The type int[] says the variable refers to an array of int values, and new int[5] creates one with five elements. The number of elements is the array's length. A program reads it as emptySeats.length, with no parentheses, since length is an attribute and not a method.
Here the length is 5, and it stays 5. If the train adds a sixth car, the program needs a new array of length 6, because the old one can't grow.
So right after that statement, every car shows 0 empty seats. That's the default, and nobody counted anything. The other element types behave the same way.
double[] carWeights = new double[5];
boolean[] quietCar = new boolean[5];
String[] carNames = new String[5];
Every element of carWeights starts at 0.0 and every element of quietCar at false. Each element of carNames holds null, which means it doesn't refer to any String yet.
An initializer list
When the values are known as the code is written, an initializer list creates the array and fills it in one statement.
int[] emptySeats = {12, 0, 31, 7, 18};
This declaration takes the place of the one above. There's no new and no length in brackets. The braces hold five values, so the array's length is 5, and the values fill the elements in the order they're written.
Accessing an element
Square brackets with an index name one element. Indexes start at 0, so emptySeats[0] is 12, the first car, and emptySeats[4] is 18, the fifth.
An element can be read and assigned like any variable of its type.
emptySeats[2] = emptySeats[2] - 9;
emptySeats[1] = emptySeats[3] + 1;
The first statement reads 31 from index 2, subtracts the 9 riders who boarded, and stores 22 back in the same element. The second reads 7 from index 3 and stores 8 at index 1. The array now holds 12, 8, 22, 7, and 18. It's the same array object as before; only two of its elements changed.
The index can be any int expression, such as a variable whose value is set while the program runs.
An index out of range
The train has no car at index 5. Since the length is 5, the last valid index is 4, and the statement emptySeats[5] = 3; compiles but throws an ArrayIndexOutOfBoundsException when it runs. The compiler can't catch it, because an index is often a variable whose value isn't known until then. An index of -1 throws the same exception at the other end.