Skip to main content
Engineering LibreTexts

16.2: Accessing Elements

  • Page ID
  • When you create an array of ints, the elements are initialized to zero. Figure 8.2.1 shows a state diagram of the counts array so far.

    State diagram of an int array.
    Figure \(\PageIndex{1}\): State diagram of an int array.

    The arrow indicates that the value of counts is a reference to the array. You should think of the array and the variable that refers to it as two different things. As we’ll soon see, we can assign a different variable to refer to the same array, and we can change the value of counts to refer to a different array.

    The large numbers inside the boxes are the elements of the array. The small numbers outside the boxes are the indexes (or indices) used to identify each location in the array. Notice that the index of the first element is 0, not 1, as you might have expected.

    The [] operator selects elements from an array:

    System.out.println("The zeroth element is " + counts[0]);

    You can use the [] operator anywhere in an expression:

    counts[0] = 7;
    counts[1] = counts[0] * 2;
    counts[3] -= 60;

    Figure 8.2.2 shows the result of these statements.

    State diagram after several assignment statements.
    Figure \(\PageIndex{2}\): State diagram after several assignment statements.

    You can use any expression as an index, as long as it has type int. One of the most common ways to index an array is with a loop variable. For example:

    int i = 0;
    while (i < 4) {

    This while loop counts from 0 up to 4. When i is 4, the condition fails and the loop terminates. So the body of the loop is only executed when i is 0, 1, 2, and 3.

    Each time through the loop we use i as an index into the array, displaying the ith element. This type of array processing is often written using a for loop.

    for (int i = 0; i < 4; i++) {

    For the counts array, the only legal indexes are 0, 1, 2, and 3. If the index is negative or greater than 3, the result is an ArrayIndexOutOfBoundsException.

    • Was this article helpful?