Stack is the most efficient data structure, it follows the “Last In First Out (LIFO)” approach to store and remove an element. The Stack is easy to use as it provides several methods to perform specific operations like insertion, deletion, searching of elements, selecting the top element, and so on. It is created empty at first and then initialized using methods like “push()” or “add()” and to remove the added element use the “pop()” method.

This guide explains the usage and working of a “stack.pop()” method in Java.

How to Use Stack.pop() Method in Java?

Stack offers multiple methods to deal with its elements. One of these methods is the “pop()” method that deletes an element from the Stack. The removal of elements from the Stack is done by following the “Last In First Out” approach means the element that is inserted at the end will get removed at first. The “pop()” automatically selects the element residing at the top or head of the Stack and removes it.

The graphical representation of removing elements from the Stack is shown below. The below figure  illustrates first the insertion of elements using a “push()” method and then the removal of top elements one by one using a “pop()” method:

Syntax

The syntax of “pop()” method is given below:

stackName.pop()

Return Value

The “Stack.pop()” method returns an element residing at the top that is being removed from the Stack.

Exception

In case of an empty Stack, the “Stack.pop()” method throws an “EmptyStackException” showing there is no element to remove. To handle this exception check the emptiness of a Stack using the “isEmpty()” method before the utilization of a “pop()” method.

Have a look at the below examples to explore more about the “Stack.pop()” method.

Example 1: Remove a Single Element From Stack Using the Stack.pop() Method

In this example, a single element from the Stack gets deleted using the “pop()” method. Along with it, we utilize the “size()” method to retrieve the size of a Stack before and after the removal of an element:

import java.util.Stack;
public class StackPop {//Define the main() Method
public static void main(String[] args) {
  Stack<Object> demoStack = new Stack<Object>();
  demoStack.push("Welcome");
  demoStack.push(345);
  demoStack.push(34.231);
  demoStack.push(91456L);
 
  System.out.println("Original Stack-> " + demoStack);
  int stackSize = demoStack.size();
  System.out.println("\nSize of Stack Before the Removal of Element: " + stackSize);
 
  System.out.println("Removed Element: " + demoStack.pop());
  System.out.println("Removed Element: " + demoStack.pop());
  System.out.println("\nStack after pop operation " + demoStack);
 
  int stackSize2 = demoStack.size();
  System.out.println("Size of Stack After the Removal of Element: " + stackSize2);
}
}

The working of the above code is written below:

  • First, declare an “Object” type Stack named “demoStack” to accept all types of values. Now, initialize the created Stack with multiple data type values using the “push()” method.
  • Next, display the “demoStack” and retrieve its size or count of elements using the “size()” method and display it as well.
  • After that, remove two elements from the stack by applying the “pop()” method twice over the “demoStack”.
  • Finally, display the “demoStack” content and its size on the console window.

The below figure for the above code confirms the deletion of two elements from the Stack(demoStack):

Example 2: Remove All or Some Elements From the Stack Using the Stack.pop() Method 

The developer can use the “pop()” method with a “for” loop to remove all or a specific number of elements from the Stack. This approach is useful where the user wants to fully empty the Stack or desires to empty till the specific number of elements like clearing the overall history or only for the previous hour. The implementation for the discussed scenario is shown in the below Java code:

import java.util.Stack;
public class StackPop {
static void popAll(Stack<Object> stack) {
  OriginalStack(stack);
  for(int i = stack.size(); i > 0 ; i--) {
  System.out.println("Removing All Elements: " + stack.pop());
  }
  updatedStack(stack);
}
  • First, define a method “popAll()” that accepts a single argument of “stack” having the type of dynamic “Object”.
  • Next, use the “for” loop that iterates till the length of a “stack” in the backward direction. This loop removes an element from the Stack in each iteration using the “pop()” method.
  • Now, pass the “stack” before and after the “for” loop in the “originalStack()” and “updatedStack()” methods respectively. These methods display the size and content of a Stack before and after the removal of a top element.
static void popSome(Stack<Object> stack) {
  OriginalStack(stack);
  for(int i = 0; i != 2 ; i++) {
  System.out.println("Removing Specified Number of Elements: " + stack.pop());
  }
  updatedStack(stack);
}
  • Then, define a “popSome()” method that accepts the “stack” and utilizes a “for” loop. This loop iterates till the specified number of elements or index number and pops an element from the stack in each iteration.
  • In our case, the specified number is “2” so two elements get removed from the Stack.
  • Also, pass the provided and modified Stack “stack” into the “originalStack()” and “updatedStack()” methods respectively.
static void OriginalStack(Stack<Object> stack) {
  System.out.println("\n\nOriginal Stack Elements-> " + stack);
  int stackSize = stack.size();
  System.out.println("\nSize of Stack Before the Removal of Element: " + stackSize);
}

static void updatedStack(Stack<Object> stack) {
  System.out.println("\nStack after pop operation " + stack);
  int stackSize = stack.size();
  System.out.println("Size of Stack After the Removal of Element: " + stackSize);
}
  • After that, define the “originalStack()” and “updatedStack()” methods accepting a single argument of “stack”. 
  • These methods retrieve the size of the provided Stack by calling the “size()” method.
  • They also print the elements and retrieve the size of the “stack” on a console via the “System.out.println()” method.
public static void main(String[] args) {
  Stack<Object> demoStack1 = new Stack<Object>();
  demoStack1.push("Hello");
  demoStack1.push(345);
  demoStack1.push(34.231);
  demoStack1.push(91456L);
  Stack<Object> demoStack2 = new Stack<Object>();
  demoStack2.push("World");
  demoStack2.push(147);
  demoStack2.push(194.231);
  demoStack2.push(17653L);
  popAll(demoStack1);
  popSome(demoStack2);
}
}
  • Define a “main()” method and inside it declare two “Object” type Stacks named “demoStack1” and “demoStack2”. 
  • Then, initialize these Stacks by inserting values using the “push()” method.
  • In the end, pass these Stacks into the “popAll()” and “popSome()” methods respectively.

The generated output confirms that all and some elements are popped out from the provided Stacks:

Bonus Tip: Remove an Element From LinkedList Using the “pop()” Method

The “LinkedList” is a data structure that stores data in the form of a List, it uses the “push()” and “pop()” methods to insert and remove elements. The elements are placed and removed from the top place similar to Stack. Let’s proceed with the practical implementation to remove an element from the LinkedList:

import java.util.LinkedList;
import java.util.Stack;

public class StackPop {

static void original(LinkedList<Object> list) {
  System.out.println("\n\nOriginal LinkedList Elements-> " + list);
  int stackSize = list.size();
  System.out.println("\nSize of LinkedList Before the Removal of Element: " + stackSize);
}

static void updated(LinkedList<Object> list) {
  System.out.println("\LinkedList after pop operation " + list);
  int stackSize = list.size();
  System.out.println("Size of LinkedList After the Removal of Element: " + stackSize);
}

public static void main(String[] args) {
  LinkedList<Object> linkedData = new LinkedList<Object>();
  linkedData.push("Hello");
  linkedData.push(345);
  linkedData.push(34.231);
  linkedData.push(91456L);
  original(linkedData);

  System.out.println("Removed Single Top Element-> " + linkedData.pop());
  updated(linkedData);
}
}

In the above code block:

  • First, create two methods namely “original()” and “updated()” methods accepting the single argument of “list”. These methods retrieve the size “list” using the “size()” method and display it on the console along with the containing elements.
  • Define a “main()” method that contains the dynamic(Object) type LinkedList named “linkedDate”. Insert element into this List using the “push()” method. 
  • After that, remove a single element from this List from the top position using the “pop()” method. Also, pass the list into the “original()” and “updated()” methods to display the contents and size of the List before and after the removal of the element.

The generated output appears like this:

Note: The “pop()” method also allows the developer to remove an element from the data structures like “Deque”, “Array”, “Queue”, and many more. The procedure remains the same as described in the removal of elements from the Stack and LinkedList sections.

How to Fix EmptyStackException?

The “EmptyStackException” is mostly raised while working with the “Stack.pop()” method. It occurs when a user tries to remove an element from an empty Stack and the “pop()” method finds no element to remove:

To fix this “EmptyStackException” check the emptiness of the Stack before removing the element using the “isEmpty()” method:

import java.util.*;
public class StackPop {
public static void main(String[] args) {
//Defining the Targeted Stack
  Stack<Object> stack = new Stack<Object>();
  stack.push("sdsd");
  stack.push("ssdsd");
  System.out.println("\nElements in the Stack -> " + stack);

  try{
  stack.isEmpty();
  System.out.println("Removed Single Element Using pop() -> " + stack.pop());
  System.out.println("\nStack After the Removal of Elements -> " + stack);
  }
  catch(Exception e)
  {
  System.out.println("\nException is Raised Because no Element is Available for Removal");
  }
}
}

The above code is similar to one already discussed in the above sections:

  • Only the “try/catch” block is used to catch the exceptions and to print the exception details on the console.
  • Then, the “isEmpty()” method is applied over the Stack “stack” to check its emptiness and after that, the “pop()” method is used.
  • Now, the “pop()” method will not execute when the Stack is empty.  

The below gif shows the fixing of the “EmptyStackException” exception along with its occurrence:

That’s all about the usage and working of a “Stack.pop()” method in Java.

Conclusion

Stack efficiently stores data using the “First In First Out(FIFO)” approach. The developer widely uses the Stack for the allocation and automatic deallocation of memory, it also removes the unusable or unrequired object automatically after a specific time or manually. For manual, deallocation and removal of objects use the “pop()” method with no argument. This method does not accept any argument and automatically selects and removes an element from the Stack that resides at the top. This “pop()” method can be used with other data structures like LinkedList and Queue to remove the top element. This article has explained the working of a “Stack.pop()” method.