Next: Practice. Up: Arrays. Previous: The array type.


Accessing array elements

To use arrays, you can use the subscript operator, a set of brackets. Into the brackets go the index of the element we're trying to access. For example, we might do the following.

IO.println(pows[2] + pows[4]);
In this example, we load array elements 2 and 4 (the third and fifth elements, 0.25 and 0.0625), add them together, and finally print the sum (0.3125).

We can also use array indices on the left-hand side of an assignment operator to change the value at a location in the array.

scores[0] = 23;

Frequently, when you access an array, you'll want to use a for loop to go through all the possible array elements. For example, the following code block would set all the array elements of scores to be 100.

for(int i = 0; i < scores.length; i++) {
    scores[i] = 100;
}
This illustrates the use of length, an instance variable for the array which represents how many array elements it has (30). For each of the integers i from 0 up to scores.length, we set array element i to be 100.


Next: Practice. Up: Arrays. Previous: The array type.