What is stack.pop() in Java?

The stack.pop() function in Java returns the element that is available at the top of the stack and removes that element from the stack.

Figure 1 shows the visual representation of the stack.pop() function:

Figure 1: Visual representation of stack.pop() function

The following module is required in order to use the function java.util.*.

Syntax


stack_name.pop();
// where the stack_name is the name of the stack

Parameter

This function does not require a parameter.

Return value

This function returns the element available at the top of the stack and removes that element from the stack.

Code

import java.util.*;
class JAVA {
public static void main( String args[] ) {
Stack<Integer> Stack = new Stack<Integer>();
Stack.add(0);
Stack.add(2);
Stack.add(5);
Stack.add(3);
Stack.add(1);
//Stack = 0->2->5->3->1
System.out.println("Following are the elements in Stack before removing: " + Stack);
System.out.println("The element removed from the front of Stack: "+Stack.pop());
System.out.println("Following are the elements in Stack after removing: " + Stack);
}
}

Free Resources