-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Learn Java with Projects
By :

In order to access elements in an array, we need to use their index. The index represents the position in the array. This allows us to retrieve the value at a certain position and assign it a new value. Let’s first talk about indexing.
In Java, arrays use zero-based indexing, which means the first element has an index of 0
, the second element has an index of 1
, and so on. Take a look at our example of the ages
array:
int[] ages = {31, 7, 5, 1, 0};
This means that the first element (31
) has an index of 0
and the last element has an index of 4
.
Figure 6.1 – Indexing explained with the ages array
We count the length of an array like we normally do, starting with 1
. So, the length of this array would be 5
. The last element in the array has an index equal to the array’s length minus 1
. For an array with a length of N, the valid indexes are in the range of 0 to N-1.
It is...