Java LinkedList pop() push() Methods Tutorial

In this section, we will learn what the LinkedList pop() and push() methods are and how to use them in Java.

What is Java LinkedList pop() Method?

The Java LinkedList pop() method is used to get the first (head) element of a LinkedList object and return that as a result.

Note: this method removes the first element from the list as well.

Java pop() Method Syntax:

public E pop()

pop() Method Parameters:

The method does not take an argument.

pop() Method Return Value:

The return value of this method is the head (first) element of the target LinkedList object.

pop() Method Exceptions:

The method might throw one exception and that is:

NoSuchElementException: We get this exception if the target list was in fact empty!

Example: using LinkedList pop() method

import java.util.LinkedList; 
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.push("John");
        list.push("Omid");
        list.push("Jack");
        list.push("Ellen");
        list.push("Elon");

        System.out.println("The size of the list before calling the pop() method: "+list.size());
        System.out.println(list.pop());
        System.out.println("The size of the list after calling the pop() method: "+list.size());
    }
}

Output:

The size of the list before calling the pop() method: 5

Elon

The size of the list after calling the pop() method: 4

What is Java LinkedList push() Method?

The Java LinkedList push() method is used to add a new element to the head of a LinkedList object.

Java push() Method Syntax:

public void push(E e)

push() Method Parameters:

The method takes one argument and that is the element we want to add to the head of the target LinkedList object.

push() Method Return Value:

The return value of the method is void.

push() Method Exceptions:

The method does not throw an exception.

Example: using LinkedList push() method

import java.util.LinkedList; 
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.push("John");
        list.push("Omid");
        list.push("Jack");
        list.push("Ellen");
        list.push("Elon");

        for (String s: list){
            System.out.println(s);
        }
    }
}

Output:

Elon

Ellen

Jack

Omid

John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies