Sub topic 1
What an Array Is
An array is a group of values stored in a fixed number of places. Each place is called an element. Arrays help you keep related values together, such as the scores for a quiz.
An array’s elements all have the same type. A type tells Java what kind of value a place can hold. For example, int is a type for whole numbers.
Declaring, Creating, and Initializing Arrays
A variable is a named place you can use to refer to a value. A declaration tells Java the variable’s name and type. For an array of whole numbers, the type is int[].
Creating an array gives it a fixed number of elements. Initializing an array means giving its elements starting values. An initializer is a list of those values inside braces, such as {80, 90, 100}.
The program below creates one array with an initializer and another with new. The second array has three elements, all starting at zero.
Save it as Main.java. Then run javac Main.java followed by java Main.
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
int[] blankScores = new int[3];
scores[1] = 95;
for (int index = 0; index < scores.length; index++) {
System.out.println(index + ": " + scores[index]);
}
int total = 0;
for (int score : scores) {
total += score;
}
System.out.println("Total: " + total);
}
}Indexes, Length, and Bounds
An index is a number that identifies an element’s place in an array. Indexes start at zero, not one. In the example, scores[1] is the second element, so the assignment changes 90 to 95.
The length is the number of elements. Use scores.length to get it. For a nonempty array, the last valid index is one less than its length. An empty array has no valid indexes.
Bounds are the limits on valid indexes. Using an index outside those limits causes an ArrayIndexOutOfBoundsException, an error that stops the program unless it is handled.
Traversing Arrays
Traversal means visiting elements one by one. The first for loop in the example uses an index. Its condition, index < scores.length, keeps the index within bounds.
The second loop is an enhanced for loop. It takes each value in turn without using an index. The loop adds the values to total, so the program prints a total of 275. Use an indexed loop when you need the position; use an enhanced loop when you only need each value.
Exercise
After the assignment in the example, what is scores[2], and what happens if you read scores[3]?
Show answer
scores[2] is 100. Reading scores[3] causes an index error because the valid indexes are 0, 1, and 2.