What is the Stack.pop method in Java?

The pop method of the Stack class can remove the topmost element of the Stack. The pop() method is available in the java.util.Stack package of Java.

Syntax


stack.pop()

Return value

This method returns the removed element as the return value. If the Stack is empty, then the EmptyStackException is thrown.


Stack is a data structure that follows the Last-In-First-Out (LIFO) principle. We use it to store the collection of objects.

Code

import java.util.Stack;
class StackPopExample {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// add elememts
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("The Stack is: " + stack);
System.out.println("Stack pop : " + stack.pop());
System.out.println("The Stack is: " + stack);
System.out.println("Stack pop : " + stack.pop());
System.out.println("The Stack is: " + stack);
System.out.println("Stack pop : " + stack.pop());
System.out.println("The Stack is: " + stack);
}
}

Explanation

In the code above, we have created a Stack object and added three elements 1,2,3 to it. We then used the pop method to remove the topmost element of the Stack.

Free Resources