E.2. Arrays

An array is a group of variables (called elements or components) containing values that all have the same type. Arrays are objects, so they’re considered reference types. As you’ll soon see, what we typically think of as an array is actually a reference to an array object in memory. The elements of an array can be either primitive types or reference types (including arrays, as we’ll see in Section E.9). To refer to a particular element in an array, we specify the name of the reference to the array and the position number of the element in the array. The position number of the element is called the element’s index or subscript.

Figure E.1 shows a logical representation of an integer array called c. This array contains 12 elements. A program refers to any one of these elements with an array-access expression that includes the name of the array followed by the index of the particular element in square brackets ([]). The first element in every array has index zero and is sometimes called the zeroth element. Thus, the elements of array c are c[0], c[1], c[2] and so on. The highest index in array c is 11, which is 1 less than 12—the number of elements in the array. Array names follow the same conventions as other variable names.

Image

Fig. E.1 | A 12-element array.

An index must be a nonnegative integer. A program can use an expression as an index. For example, if we assume that variable a is 5 and variable b is 6, then the statement

c[ a + b ] += 2;

adds 2 to array element c[11]. An indexed array name is an array-access expression, which can be used on the left side of an assignment to place a new value into an array element.

Let’s examine array c in Fig. E.1 more closely. The name of the array is c. Every array object knows its own length and stores it in a length instance variable. The expression c.length accesses array c’s length field to determine the length of the array. Even though the length instance variable of an array is public, it cannot be changed because it’s a final variable. This array’s 12 elements are referred to as c[0], c[1], c[2],..., c[11]. The value of c[0] is -45, the value of c[1] is 6, the value of c[2] is 0, the value of c[7] is 62 and the value of c[11] is 78. To calculate the sum of the values contained in the first three elements of array c and store the result in variable sum, we would write

sum = c[ 0 ] + c[ 1 ] + c[ 2 ];

To divide the value of c[6] by 2 and assign the result to the variable x, we would write

x = c[ 6 ] / 2;

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset