Java Stack - pop() Method
The java.util.Stack.pop() method deletes the top element of the stack and returns the deleted element as the value of this method. In a stack, addition and deletion of a element occurs from the top of the stack. Hence, the most recently added element will be the top element of the stack. Every deletion of element results into reducing the stack size by one unless the stack is empty.
Syntax
public E pop()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
returns the deleted element of the stack.
Exception
Throws EmptyStackException, if this stack is empty.
Example:
In the example below, the java.util.Stack.pop() method is used to delete the top element of the stack called MyStack.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a stack Stack<Integer> MyStack = new Stack<Integer>(); //populating stack MyStack.push(10); MyStack.push(20); MyStack.push(30); //deleting top element System.out.println(MyStack.pop() + " is deleted from MyStack."); //printing stack System.out.println("MyStack contains: " + MyStack); } }
The output of the above code will be:
30 is deleted from MyStack. MyStack contains: [10, 20]
❮ Java.util - Stack