Java ArrayDeque pop()

In this guide, you will learn about the ArrayDeque pop() method in Java programming and how to use it with an example.

1. ArrayDeque pop() Method Overview

Definition:

The pop() method of the ArrayDeque class in Java is used to pop an element from the stack represented by this ArrayDeque. This method retrieves and removes the first element of the ArrayDeque.

Syntax:

public E pop()

Parameters:

This method does not take any parameters.

Key Points:

- The pop() method retrieves and removes the first element of the ArrayDeque.

- This method is equivalent to removeFirst().

- If the ArrayDeque is empty, the pop() method will throw a NoSuchElementException.

- The ArrayDeque class is not thread-safe, and external synchronization is necessary if it is accessed by multiple threads concurrently.

- The ArrayDeque class does not allow null elements.

2. ArrayDeque pop() Method Example

import java.util.ArrayDeque;

public class ArrayDequeExample {

    public static void main(String[] args) {
        ArrayDeque<Integer> deque = new ArrayDeque<>();

        // Adding elements to the ArrayDeque
        deque.add(1);
        deque.add(2);
        deque.add(3);

        // Printing the original ArrayDeque
        System.out.println("Original ArrayDeque: " + deque);

        // Using pop() to remove the first element
        Integer poppedElement = deque.pop();

        // Printing the popped element and the ArrayDeque after pop operation
        System.out.println("Popped Element: " + poppedElement);
        System.out.println("ArrayDeque after pop: " + deque);

        // Trying to pop from an empty ArrayDeque will throw NoSuchElementException
        deque.clear();
        try {
            deque.pop();
        } catch (NoSuchElementException e) {
            System.out.println("Cannot pop from an empty ArrayDeque.");
        }
    }
}

Output:

Original ArrayDeque: [1, 2, 3]
Popped Element: 1
ArrayDeque after pop: [2, 3]
Cannot pop from an empty ArrayDeque.

Explanation:

In this example, we initialize an ArrayDeque and add some elements to it. 

We then use the pop() method to remove the first element of the ArrayDeque, and we print the state of the ArrayDeque before and after the pop() operation. The popped element is also printed. 

Finally, we demonstrate that trying to pop from an empty ArrayDeque results in a NoSuchElementException.

Comments