Get first and last element of an array in Java

In this post, I will be sharing how to get the first and last element of an array in Java. We will first understand the question with the help of examples before moving on to the solution.

Read Also:  Array Interview Questions and Answers in Java

Example 1

Given Integer array is:
 [12, 81, 17, 13, 53, 25]

 Output: firstElement:12, lastElement:25


Example 2

Given String array is:
 ["Alive", "is", "Awesome"]

 Output: firstElement:Alive lastElement:Awesome


Let's dive deep into the topic:

Get first and last element of an array in Java


get first and last element of an array in Java

1. Get first and last element of a String array


Java program to get the first and last element of a String array is given below:

 public class FirstLastElementArray {
    public static void main(String args[]) {
      // Given string array
      String[] str = new String[]{"Alive","is", "Awesome"};
      // Getting first element of a string array
      String first = str[0];
      // Getting last element of a string array
      String last = str[str.length -1];
      // Print first element of a string array
      System.out.println("First element is: "+first);
      // Print last element of a string array
      System.out.println("Last element is: "+last);
    }
}


Output:
First element is: Alive
Last element is: Awesome



2. Get first and last element of an Integer array


Java program to get the first and last element of an Integer array is given below:

 public class FirstLastElementArray2 {
    public static void main(String args[]) {
      // Given array
      Integer[] numbers = new Integer[]{12, 34, 23, 65, 99};
      // Getting first element of an array
      Integer first = numbers[0];
      // Getting last element of an array
      Integer last = numbers[numbers.length -1];
      // Print first element of an array
      System.out.println("First element is: "+first);
      // Print last element of an array
      System.out.println("Last element is: "+last);
    }
}


Output:
First element is: 12
Last element is: 99


That's all for today. Please mention in the comments if you have any questions related to how to get the first and last element of an array in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry