Java ArrayDeque push()

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

1. ArrayDeque push() Method Overview


The push() method of the ArrayDeque class in Java is used to push an element onto the stack represented by the ArrayDeque. This method inserts the element at the front of the ArrayDeque.


public void push(E e)


- e: The element to add.

Key Points:

- The push() method inserts the specified element at the front of the ArrayDeque.

- This method is equivalent to addFirst(E).

- The ArrayDeque class is a resizable array implementation of the Deque interface.

- ArrayDeque does not support the addition of null elements. Attempting to add null to an ArrayDeque will result in a NullPointerException.

- The ArrayDeque class is not thread-safe, so external synchronization is necessary if an ArrayDeque instance will be accessed by multiple threads concurrently.

2. ArrayDeque push() Method Example

import java.util.ArrayDeque;

public class ArrayDequeExample {

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

        // Adding elements using add() method

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

        // Using push() to add an element at the front

        // Printing the ArrayDeque after push operation
        System.out.println("ArrayDeque after push: " + deque);

        // Trying to push null to the ArrayDeque will throw NullPointerException
        try {
        } catch (NullPointerException e) {
            System.out.println("Cannot push null to an ArrayDeque.");


Original ArrayDeque: [1, 2, 3]
ArrayDeque after push: [0, 1, 2, 3]
Cannot push null to an ArrayDeque.


In this example, we initialize an ArrayDeque and add some elements using the add() method. 

We then use the push() method to insert the element 0 at the front of the ArrayDeque. The state of the ArrayDeque is printed before and after the push() operation. 

Finally, we demonstrate that trying to push null to the ArrayDeque results in a NullPointerException.