Java ProgramsCollectionsStack Example

Stack Example in Java

beginner·  Collections  ·  Queue & Stack

Problem

A Stack is a last-in-first-out structure — the most recently added element is always the first one removed, the opposite order from a queue.

Push a series of plates onto a Stack, then pop and peek to see which ones come off first.

Input
push(Plate1), push(Plate2), push(Plate3)
Output
Top: Plate3 Popped: Plate3 Popped: Plate2 Popped: Plate1

Java Program

Java
import java.util.Stack; public class StackExample { public static void main(String[] args) { Stack<String> plates = new Stack<>(); plates.push("Plate1"); plates.push("Plate2"); plates.push("Plate3"); System.out.println("Top: " + plates.peek()); // reads without removing while (!plates.isEmpty()) { System.out.println("Popped: " + plates.pop()); } } }

Output

Top: Plate3 Popped: Plate3 Popped: Plate2 Popped: Plate1

Core Logic

Every push() adds to the top of the stack, and every pop() removes from that same top — the last plate pushed is always the first one popped back off.

How It Works
  1. 1plates.push("Plate1"), then "Plate2", then "Plate3" stack three plates, with Plate3 ending up on top.
  2. 2plates.peek() reads the top element without removing it, confirming Plate3 is currently on top.
  3. 3plates.pop() removes and returns the top element, which is Plate3 first, exposing Plate2 as the new top.
  4. 4Repeating pop() continues unwinding the stack in exactly the reverse order the plates were pushed.
Pushing Plate1, Plate2, Plate3 in that order and then popping repeatedly returns them as Plate3, Plate2, Plate1 — last in, first out.
💡

Key Point: peek() and pop() both throw EmptyStackException if the stack has nothing left in it — checking isEmpty() first avoids that when the stack's contents aren't already known.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: Stack extends Vector and operates only at the end of its backing array, so push(), pop(), and peek() are all constant-time regardless of how many elements are on the stack.

Key Concepts

Stackpush()pop()peek()

Related Programs