Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of Stack.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of Stack.

Objective

Write a Java program to demonstrate the LIFO behavior of a Stack.

Algorithm / Approach

  1. Create a Stack object.
  2. Create a method to insert data using st.push(a).
  3. Create a method to extract data using st.pop().
  4. Push three items onto the stack (20, 40, 60).
  5. Pop items off the stack one by one, observing that 60 comes off first.
  6. Attempt to pop from an empty stack inside a try-catch block to handle the EmptyStackException.
Test.java
import java.util.*;
class Test {
 void insert(Stack st, int a) {
  st.push(a);
  System.out.println("Adding "+a);
  System.out.println("stack: "+st);
 }
 void delete(Stack st) {
  System.out.print("Remove ");
  int a = (int) st.pop();
  System.out.println(a);
  System.out.println("stack: "+st);
 }
 public static void main(String[] a)
 {
  Stack st = new Stack();
  Test t = new Test();
  System.out.println("stack: "+st);
  t.insert(st, 20);
  t.insert(st, 40);
  t.insert(st, 60);
  t.delete(st);
  t.delete(st);
  t.delete(st);
  try {
   t.delete(st);
  }catch (Exception e) {
   System.out.println("empty stack");
  }
 }
}

Expected Output

stack: []
Adding 20
stack: [20]
Adding 40
stack: [20, 40]
Adding 60
stack: [20, 40, 60]
Remove 60
stack: [20, 40]
Remove 40
stack: [20]
Remove 20
stack: []
Remove empty stack

Explanation of the Program

  • A Stack is a legacy class that extends Vector and represents a Last-In-First-Out (LIFO) data structure.
  • Think of it like a stack of plates: the last plate you put on top of the stack (push) is the very first plate you have to take off (pop).
  • If you call pop() when there are no items left in the stack, the JVM throws an EmptyStackException.

Complexity

Time Complexity O(1) - For push and pop operations.
Space Complexity O(n)
ADVERTISEMENT