Beginners Programs :

Java : Return the Last Element in An Array & N Elements | Java Programs

 Java program to return the last element in an array – Here we written the program in four different ways to find the last element of array in Java along with outputs as well.Get last

Print Last Element – Static Method

Here, our problem statement is to find the last element in the given array. For this, our required inputs are the total number of elements in the array or the size of array and the data values in the array.

Our desired output is the last element among these entered data values in the array.

To read the required inputs, we use the Scanner class. For any primitive datatype, this can be used. We first create an object of Scanner class and then, we invoke the nextInt() method since, all the inputs are of integer type. Then, we read the number of elements and each element of the array from console screen by using the nextInt() method.

After getting the inputs, we call the static method (LastElement) and pass the array as argument. To calculate the length of the array, we have a predefined method arrayname.length. So, we make use of this method to find the last element. Since indexing of array starts from zero, the last element would be in the index length-1. So, if the length is zero, it means it has no elements so, we return zero to the main method else, we return the  last element i.e., a[length-1]. This returned value is displayed on the console screen using the println() method.

if(a.length==0) {

System.out.println(“Array is Empty”);

return 0;

}

return a[a.length-1];

Here is the Java Code

Output:

Here, array a[]= { 12, 97, -50}

Length of array = 3

a[0]=12, a[1]=97, a[2]=-50

therefore, a[length-1]=a[3-1]-a[2]=-50 which is the last element.

Java Getting the Last Three Elements from A List/array List

Instead of using a separate static method, we can write the entire code within main method. But, if this is done then, it is not reusable. So, we first read the total number of elements (n) and the individual elements of array (a).

If the total number of elements (n) is equal to zero then, the array is empty so, we give this warning and stop the execution.

Else, we read the elements in the array and the last element of the array would be at index n-1. Because, the indexing starts from zero so, the last element of an array of length n would be at (n-1)th  position i.e., a[n-1]. This value is displayed and we reach the end of execution.

Output: