![]() |
VOOZH | about |
In Java, to get the last element in an array, we can access the element at the index array.length - 1 using array indexing. The length property of the array provides its total size, and subtracting one from it gives the index of the last element.
Example 1: Here, we will access the last element in an Integer array.
5
arrayName[arrayName.length - 1];
Example 2: Here, we will access the last element in an array of Strings.
Blueberry
Example 3: If we try to access the last element of an empty array, it will throw an ArrayIndexOutOfBoundsException.
The array is empty.