Open In App

LinkedList getLast() Method in Java

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the getLast() method in the LinkedList class is used to retrieve the last element of the list.

Example 1: Here, we use the getLast() method to retrieve the last element of the list.

Java
// Java Program to Demonstrate the 
// use of getLast() in LinkedList
import java.util.LinkedList;

public class Geeks {
    public static void main(String args[]) {
      
        // Create an empty list
        LinkedList<String> l = new LinkedList<>();

        // Use add() to add
        // elements in the list
        l.add("Geeks");
        l.add("for");
        l.add("Geeks");

        System.out.println("" + l);

        // Use getLast() to display the 
        // last element of the list
        System.out.println("" + l.getLast());
    }
}

Output
[Geeks, for, Geeks]
Geeks

Syntax of LinkedList getLast() Method

public E getLast()

Return type: It return the last element of the list.

LinkedList getLast() Method work flow


Example 2: Here, the getLast() method throws an NoSuchElementException if the list is empty.

Java
// Throws NoSuchElementException
import java.util.LinkedList;

class Geeks {
    public static void main(String[] args) {
      
        // Create an empty list
        LinkedList<Integer> l = new LinkedList<>();
      
        // Use add() to add 
        // elements in the list
        l.add(10);
        l.add(20);
        l.add(30);
        l.add(40);
        l.add(50);
      
        // Use getLast() to get the 
        // last element of the list
        System.out.println("The last element of the LinkedList is: "
                           + l.getLast());
      
        // Use clear() to clear the list
        l.clear();

        // Trying to get the last 
        // element from an empty list
        try {
            System.out.println(
                "Last element of LinkedList is: "
                + l.getLast());
        }
        catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

Output
The last element of the LinkedList is: 50
Error: java.util.NoSuchElementException


Next Article

Similar Reads