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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.