Data Structure & Algorithm in Java

  1. Home
  2. Docs
  3. Data Structure & Alg...
  4. Stack
  5. Basic Concept of stack

Basic Concept of stack

  • Most Importantly Insertion of an element into stack are called PUSH operation.
  • And ,Deletions of an element from stack are called as POP operation.
  • Plus, when the stack is full it is said to “STACK OVERFLOW“.
  • And, when the stack becomes empty it is referred as “STACK UNDERFLOW“.
stack operations

2.) Pop: This operation removes the top element from the stack.

stack pop operation1510464500785197077

3.) Empty: Tests if this stack is empty.

pmcnxxSMU6 emptystack
image 96
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        // Create a stack
        Stack<Integer> stack = new Stack<>();

        // Push elements onto the stack

        // Print the stack
        System.out.println("Stack: " + stack);

        // Pop an element from the stack
        int poppedElement = stack.pop();
        System.out.println("Popped element: " + poppedElement);

        // Peek at the top element of the stack
        int topElement = stack.peek();
        System.out.println("Top element: " + topElement);

        // Check if the stack is empty
        System.out.println("Is stack empty? " + stack.isEmpty());

        // Search for an element in the stack
        int index =;
        if (index != -1) {
            System.out.println("Element 2 found at index " + index + " from the top of the stack.");
        } else {
            System.out.println("Element 2 not found in the stack.");
Stack: [1, 2, 3]
Popped element: 3
Top element: 2
Is stack empty? false
Element 2 found at index 1 from the top of the stack.
Advantages of Stack
Disadvantages of Stack

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *