8.2 Accessing Array Elements

Elements of an array are accessed using this syntax:

arrayName[exp]
   where exp is an expression that evaluates to an integer.

Exp is the element’s position, or index, within the array. The index of the first element in the array is always 0; the index of the last element is always 1 less than the number of elements.

Arrays have a read-only, integer instance variable, length, which holds the number of elements in the array. To access the number of elements in an array named arrayName, use this syntax:

arrayName.length

Thus, to access the last element of an array, use this syntax:

arrayName[arrayName.length - 1]

Note that regardless of the data type of the elements in an array, the length of an array is always an ...

Get Java Illuminated, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.