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

Learn Java with Projects
By :

To avoid getting exceptions, we need to stay within the bounds of the array. Indexes always start at 0
, and they end at the length of the array minus 1
. If you try to access an element outside this range, you’ll get ArrayIndexOutOfBoundsException
. The key to avoiding this is working with the length of the array.
We can determine the length of an array using the length
property. The length
property returns the number of elements in the array. For example, to get the length of our ages
array, we can use the following code:
int arrLength = ages.length;
The length of the array starts counting at 1
. Therefore, the length of our ages
array is 5
. The maximum index is 4
.
If you try to access or modify an array element using an invalid index (an index that is less than 0 or greater than or equal to the array’s length), Java throws ArrayIndexOutOfBoundsException...