Remove an element from a Stack in Java



An element can be removed from a stack using the java.util.Stack.pop() method. This method requires no parameters and it removes the element at the top of the stack. It returns the element that was removed.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack); System.out.println("The element that was popped is: " + stack.pop()); System.out.println("The stack elements are: " + stack); } }

Output

The stack elements are: [Apple, Mango, Guava, Pear, Orange] The element that was popped is: Orange The stack elements are: [Apple, Mango, Guava, Pear]

Now let us understand the above program.

The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed. A code snippet which demonstrates this is as follows −

Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack);

The Stack.pop() method is used to remove the top element of the stack and display it. Then the stack is again displayed. A code snippet which demonstrates this is as follows −

System.out.println("The element that was popped is: " + stack.pop()); System.out.println("The stack elements are: " + stack);
Updated on: 2019-07-30T22:30:24+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements