How to get the first and last element of an array in Java

Hi coders! In this tutorial, we are going to discuss a very famous problem to Array. Today’s topic is how to get the first and last element of an array in Java.

Array is a linear data structure which stores a set of same data in a continuous manner.  Array is a very useful data structure since it can store a set of data in a manner so that any operation on the data is easy.

Program to get the first and last element of an array in Java

int a[]=new int[5];
a={1,2,3,4,5};

The above code is declaration and definition of an  array in java.

Array indexing always starts with zero. So, In the above code the indexing of all elements are:

  • At index 0 element is 1
  • At index 1 element is 2
  • At index 2 element is 3
  • At index 3 element is 4
  • At index 4 elements is 5
class CodeSpeedy
{
public static void main(String args[])
{
int a[]=new int[5];
a={1,2,3,4,5};
int size=a.length;
System.out.println("First element of an array is"+a[0]);
System.out.println("Last element of an array is "+a[size-1]);
}
}

Here, we assign the length of an array to the size variable, we use the inbuilt function of array class that is length () which will give us the length of an array that is the count of elements present in array.

array.length: length is a final variable applicable for java arrays. With the help of the length variable, we can obtain the size of the array

So if we want to print the last element of an array, it will always present at length of an array minus 1.

Here, in our case, the length of the array is 5 so the last element is present at (5-1=4) 4th position.

OUTPUT:

First Element of an array is 1

Last element of an array is 5

 

Leave a Reply

Your email address will not be published. Required fields are marked *