To get the last element of an array in Java, you can use the length
field of the array to get the size of the array, and then access the element at the index length - 1
.
Here's an example of how you can get the last element of an array in Java:
int[] numbers = {1, 2, 3, 4, 5}; int last = numbers[numbers.length - 1];
In this example, the numbers
array is an integer array containing five elements. The last
variable holds the value of the last element, which is 5
.
You can use this approach to get the last element of any type of array, as long as the array has at least one element. If the array is empty, accessing the element at index length - 1
will cause an ArrayIndexOutOfBoundsException
to be thrown.