Arrays
An array is a set of values of one type stored under one name. Instead of ten variables price1, price2 and so on, you create one array prices. An array has a fixed length: it is set at creation and never changes afterwards.
Creating an array
An array type is written as the element type with square brackets: int[], String[]. If the values are known right away, list them in curly braces:
void main() {
int[] scores = {90, 75, 82};
IO.println(scores[0]);
IO.println(scores.length);
}Output:
90
3An element is accessed by its index — a number in square brackets. Numbering starts at zero, so three elements have indexes 0, 1 and 2. The length field holds the array's length.
Changing elements
An array element works like a regular variable: you can assign it a new value by index:
void main() {
String[] names = {"Anna", "Oleg", "Maria"};
names[1] = "Igor";
IO.println(names[0] + ", " + names[1] + ", " + names[2]);
}Output:
Anna, Igor, MariaAn empty array of a given length
When the values will come later, the array is created with the word new and the length in brackets. The elements immediately get default values: 0 for numbers, false for boolean, null for strings and other objects:
void main() {
int[] counts = new int[3];
String[] labels = new String[2];
counts[0] = 5;
IO.println(counts[0] + " " + counts[1] + " " + counts[2]);
IO.println(labels[0]);
}Output:
5 0 0
nullnull means "no object". You cannot call a method on such an element — the program would crash with an error.
Looping over an array
Arrays are almost always processed in a loop. A regular for gives you the index, for-each gives you the values directly:
void main() {
double[] prices = {4.5, 3.0, 2.5};
double total = 0;
for (int i = 0; i < prices.length; i++) {
IO.println((i + 1) + ". $" + prices[i]);
}
for (double price : prices) {
total += price;
}
IO.println("Total: $" + total);
}Output:
1. $4.5
2. $3.0
3. $2.5
Total: $10.0Printing an array
To print a whole array, use Arrays.toString() — it collects all elements into a string in square brackets:
void main() {
int[] numbers = {3, 1, 2};
IO.println(Arrays.toString(numbers));
}Output:
[3, 1, 2]The Arrays class can also sort, copy and compare arrays — see the lesson on the Arrays class.
Common mistake
If you print an array directly, you get cryptic text instead of the elements:
void main() {
int[] numbers = {3, 1, 2};
IO.println(numbers);
}Output (the digits after @ change from run to run):
[I@27c6e487This is an internal description of the object: [I means "an int array", followed by its hash code. To print the contents, always use Arrays.toString().