OneBite.Dev - Coding blog in a bite size

get the last element of array in java

Code snippet on how to get the last element of array in java

int array[] = {1, 2, 3, 4, 5};
int lastElement = array[array.length - 1];

This code finds the last element of the given array, which in this case is 5. It does this by first creating an array of five elements (1, 2, 3, 4, 5). Then, it creates an int variable called lastElement which is equal to the value of the last element in the array. To do this, it uses the length of the array, which is 5, and subtracts 1, to get the last index of the array, which is 4. Then, it stores the value of the element at index 4 in the array, which is 5, into the variable lastElement.

java