1. Introduction

In Java, an ArrayList is a part of the java.util package and is used to store dynamically sized collections of elements. It is often useful to retrieve the first and last elements from an ArrayList. This post will demonstrate how you can get the first and last elements of an ArrayList in Java.

2. Program Steps

1. Initialize an ArrayList.

2. Add elements to the ArrayList.

3. Retrieve and print the first and last elements of the ArrayList.

3. Code Program

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        // Step 1: Initialize an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();

        // Step 2: Add elements to the ArrayList
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);

        // Step 3: Retrieve and print the first and last elements of the ArrayList
        if (!numbers.isEmpty()) {
            int firstElement = numbers.get(0);
            int lastElement = numbers.get(numbers.size() - 1);

            System.out.println("First Element: " + firstElement);
            System.out.println("Last Element: " + lastElement);
        } else {
            System.out.println("The ArrayList is empty.");
        }
    }
}

Output:

First Element: 1
Last Element: 5

4. Step By Step Explanation

Step 1: An ArrayList named numbers is initialized to hold Integer values.

Step 2: Elements 1, 2, 3, 4, and 5 are added to the ArrayList.

Step 3: Before attempting to retrieve elements, a check is performed to ensure the ArrayList is not empty. The get() method is then used to retrieve the first and last elements using indices 0 and numbers.size() – 1, respectively. The retrieved first and last elements, 1 and 5, are then printed to the console.

Note: It is crucial to check whether the ArrayList is not empty before trying to access elements to avoid IndexOutOfBoundsException.