how to get last element of array java

www.l‮ttua‬uri.com
how to get last element of array java

To get the last element of an array in Java, you can use the length field of the array to get the number of elements, 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 array of integers containing five elements, and the last variable holds the last element of the array, which is the element at index 4.

It's important to note that the index of the first element in an array is 0, and the index of the last element is length - 1. You should ensure that the array has at least one element before attempting to access the last element.

Created Time:2017-11-01 20:42:55  Author:lautturi