Arrays
An array is a fixed-length sequence of values of one type. The length is chosen when the array is created and does not change, which is the difference between an array and the collections of the later part of the course. The elements sit next to each other in one object, and an index from 0 to length - 1 reaches each one in constant time.
Creating an array
There are two forms. new int[3] creates three elements with default values, and {10, 20, 30} creates the array and fills it in one expression. The second form is only legal where the compiler knows the type, which is a declaration or an argument.
The file Basics.java:
public class Basics {
public static void main(String[] args) {
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
int[] primes = {2, 3, 5, 7};
System.out.println("length: " + numbers.length);
System.out.println("first: " + numbers[0]);
System.out.println("last: " + primes[primes.length - 1]);
int total = 0;
for (int i = 0; i < numbers.length; i++) {
total += numbers[i];
}
System.out.println("total: " + total);
}
}
javac -Xlint:all Basics.java
java Basics
length: 3
first: 10
last: 7
total: 60
The brackets may follow the type or the name: int[] numbers and int numbers[] declare the same thing, and the first form is the one the language guide uses. An array is an object, so a declaration only creates the reference; new or an initialiser creates the array itself.
Default elements
A new array is filled with the default value of its element type: zero for the numeric types, false for a boolean, the NUL character for a char and null for a reference. This is the same rule as for the fields of an object, and it is why an array of objects starts as a row of nulls.
public class Defaults {
public static void main(String[] args) {
int[] numbers = new int[3];
boolean[] flags = new boolean[2];
String[] names = new String[2];
System.out.println("int: " + numbers[0]);
System.out.println("boolean: " + flags[0]);
System.out.println("String: " + names[0]);
System.out.println("length: " + numbers.length);
}
}
javac -Xlint:all Defaults.java
java Defaults
int: 0
boolean: false
String: null
length: 3
The last line is the length of the first array, printed to show that the object exists and has three elements even though none of them was assigned. A null element is not an empty string, and a method called on it throws NullPointerException.
length is a field
length is a public field of the array object, not a method: numbers.length, never numbers.length(). A string is a different object with a method length(), and mixing the two is one of the first compile errors a beginner meets.
The field is final, so the length cannot be assigned. A program that needs a longer array creates a new one and copies the old elements, which is what Arrays.copyOf does in lesson 022.
Iterating
The indexed loop is the general form: it knows the position of each element and can go backwards or skip. The enhanced form is shorter when only the values are needed.
public class Iterate {
public static void main(String[] args) {
int[] values = {4, 8, 15, 16, 23, 42};
for (int i = 0; i < values.length; i++) {
System.out.println(i + ": " + values[i]);
}
int sum = 0;
for (int value : values) {
sum += value;
}
System.out.println("sum: " + sum);
}
}
javac -Xlint:all Iterate.java
java Iterate
0: 4
1: 8
2: 15
3: 16
4: 23
5: 42
sum: 108
The index of the last element is length - 1, which is 5 for an array of six values. A loop written with i <= values.length reads one element past the end and fails on the last pass, which is the subject of the next section.
Out of bounds
Every index is checked when it is used. An index below zero or at least the length throws ArrayIndexOutOfBoundsException, and the JVM reports the length in the message. A program can catch it, and a program should usually prevent it by testing the index first.
public class Bounds {
public static void main(String[] args) {
int[] values = {1, 2, 3};
try {
System.out.println(values[3]);
} catch (ArrayIndexOutOfBoundsException error) {
System.out.println("caught: " + error.getMessage());
}
}
}
javac -Xlint:all Bounds.java
java Bounds
caught: Index 3 out of bounds for length 3
The message names the index and the length, which is enough to see the mistake: a three-element array has the indices 0, 1 and 2. The next lesson sorts and searches arrays with the methods of java.util.Arrays, and the one after writes the loops by hand.
Exercises
- Create an array of five names, leave two elements unset and print all five with an indexed loop.
- Change the loop in Basics.java to i <= numbers.length and run it. Read the message.
- Print the elements of Iterate.java backwards with one indexed loop.
- Try values.length() on an array. What does javac say?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the type of
values.length?Answer
int, a final field of the array
length is a final int field of every array object, not a method.
-
Which indices does an array of length 3 accept?
Answer
0, 1 and 2
The first index is 0 and the last is length - 1.
-
What does a new array of ints contain?
Answer
Zeros
Every element starts at the default of the element type, which is 0 for int.
-
What does this program print?
public class Q1 { public static void main(String[] args) { int[] values = new int[4]; System.out.println(values[2]); } }Answer
0
A new int array is filled with zeros, and index 2 is one of them.
-
What does this program print?
public class Q2 { public static void main(String[] args) { int[] values = {3, 6, 9}; System.out.println(values.length + " " + values[2]); } }Answer
3 9
The array has three elements and the last index is 2, whose value is 9.
-
What does this program print?
public class Q3 { public static void main(String[] args) { int[] values = {1, 2, 3}; try { System.out.println(values[3]); } catch (ArrayIndexOutOfBoundsException error) { System.out.println("caught"); } } }Answer
caught
Index 3 is out of bounds for a length of 3, and the catch prints one line.
-
What does this program print?
public class Q4 { public static void main(String[] args) { int[] values = {2, 4, 6, 8}; int total = 0; for (int value : values) { total += value; } System.out.println(total); } }Answer
20
The four values add up to 20.
-
What is the first line of the compiler output for
int n = values.length();where values is an int array?Answer
error: cannot find symbol
An array has a field length, not a method, so javac reports the unknown method.
-
What does this program print?
public class Q5 { public static void main(String[] args) { String[] names = new String[2]; names[0] = "Ada"; System.out.println(names[0] + " " + names[1]); } }Answer
Ada null
The second element was never set, so it is null, and string concatenation prints the word null.
-
What does an array declaration such as
int[] values;create?Answer
A reference that is still null
The declaration creates the reference only; the array object comes from new or an initialiser.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev