What is the Deque.removeLast() method in Java?

We use the Deque.removeLast() method to remove the element at the end of the deque. The method also returns the removed element.

The Deque.removeLast() method is present in the Deque interface inside the java.util package.

Syntax

Element removeLast(element)

Parameters

The Deque.removeLast() method doesn’t take any parameters.

Return value

The Deque.removeLast() method returns the removed element from the deque. removeLast() throws an exception error if called on an empty deque.

Code

Let us take a look at the code snippet below.

import java.util.*;
class TestingRemoveLast
{
public static void main(String[] args)
{
try
{
// Declare a Deque
Deque<Integer> deque = new LinkedList<Integer>();
// Add 7 integers to the deque
deque.add(212);
deque.add(23);
deque.add(621);
deque.add(1280);
deque.add(3121);
deque.add(18297);
deque.add(791);
// Print the deque to check the successful insertion of the integers
System.out.println("Elements in the deque are: "+deque);
// call removeLast to check if the function works well
System.out.println("Calling removeLast() returns " + deque.removeLast());
// call removeLast again to check if the function removes the last element successfully
System.out.println("Calling removeLast() returns " + deque.removeLast());
// Print the deque to check the remaining elements
System.out.println("Elements in the deque are: "+deque);
// Call removeLast() 5 times
for (int i=0; i<5; i++)
{
System.out.println("Calling removeLast() returns " + deque.removeLast());
}
// Print the deque to check the remaining elements
System.out.println("Elements in the deque are: "+deque);
// Call removeLast to test its functionality on an empty deque
// This call throws an exception which is caught in the catch block
System.out.println("Calling removeLast() returns " + deque.removeLast());
}
catch(Exception error)
{
// The exception details are printed here
System.out.println("Exception occurred: " + error);
}
}
}

Explanation

  • In line 9, we declare a deque that consists of Integer type elements.

  • In lines 11-17, we use the Deque.add() method to insert elements in the deque.

  • In line 20, we print the deque with the current elements.

  • In lines 22-24, we call the removeLast() method to remove the elements from the end of the deque.

  • In lines 29-32, we call the removeLast() method to remove all other elements from the deque.

  • In line 40, we call the removeLast() method on the empty deque. This line throws an exception error, which is caught in line 42.

  • In line 45, we print the caught exception and the error message NoSuchElementException.

Free Resources