Home »
Java programming language
Java Stack pop() Method with Example
Stack Class pop() method: Here, we are going to learn about the pop() method of Stack Class with its syntax and example.
Submitted by Preeti Jain, on March 24, 2020
Stack Class pop() method
- pop() method is available in java.util package.
- pop() method is used to return the top element from this Stack and it retrieves element with removing.
- pop() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- pop() method does not throw an exception at the time of returning top element.
Syntax:
public Object pop();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is Object, it returns head element from the stack.
Example:
// Java program to demonstrate the example
// of Object pop() method
// of Stack
import java.util.*;
public class PopOfStack {
public static void main(String args[]) {
// Instantiates Stack object
Stack s = new Stack();
// By using push() method isto
// push the given onto the stack
s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.push(50);
// Display Stack
System.out.println("s:" + s);
// By using pop() method is
// to pop the top element
// with removing from the stack
Object ele = s.pop();
// Display Popped Element
System.out.println("s.pop(): " + ele);
// Display Updated Stack
System.out.println("s:" + s);
}
}
Output
s:[10, 20, 30, 40, 50]
s.pop(): 50
s:[10, 20, 30, 40]