java

How to get the first and last elements from ArrayList in Java

In this tutorial, we are going to see how to get the first and last element of a list in Java. In Java, the first element is at index 0, we can get the last index of a list using this formula: list.size() – 1.
 

How to get the first and last elements from ArrayList in Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
      
      List<String> lang = Arrays.asList("Java", "PHP", "C++", "Python");
      
      System.out.println("The first element is: " + lang.get(0));
      
      System.out.println("The last element is: "+lang.get(lang.size()-1));   
    }
}

Output:

The first element is: Java
The last element is: Python
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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