Stack Class in Java

Naveen AnamaneniUpdated · 4 min read

Stack in Java is a class that represents a last-in, first-out (LIFO) collection of objects. It is used when the most recently added element must be the first one removed, like a pile of plates where you always take the top plate. Stack extends Vector, so it is also a legacy, synchronized class. In this lesson, you will learn the methods of Stack, see examples, and learn which class modern code uses instead.

Declaration

Declaration
public class Stack<E> extends Vector<E>

How a Stack Works

Push adds on top, pop takes from the top: last in, first out
  • push puts an element on the top.
  • pop removes the top element and returns it.
  • peek looks at the top element without removing it.

Methods of Stack

MethodDescription
E push(E item)It is used to put an element on the top of the stack.
E pop()It removes and returns the top element.
E peek()It returns the top element without removing it.
boolean empty()It returns true if the stack has no elements.
int search(Object o)It returns the 1-based position from the top, or -1 if not found.

Example: Stack Operations

Let's see an example of every method.

StackDemo.java▶ Try it
import java.util.Stack;
 
public class StackDemo {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("Navika");
        stack.push("Srihitha");
        stack.push("Advitha");
        System.out.println("Stack: " + stack);
 
        System.out.println("Top: " + stack.peek());
        System.out.println("Position of Navika: " + stack.search("Navika"));
        System.out.println("Popped: " + stack.pop());
        System.out.println("Stack: " + stack);
        System.out.println("Empty? " + stack.empty());
    }
}
Output
Stack: [Navika, Srihitha, Advitha]
Top: Advitha
Position of Navika: 3
Popped: Advitha
Stack: [Navika, Srihitha]
Empty? false

Explanation: Printing a Stack shows the bottom first and the top last, so Advitha, pushed last, is on top. peek reads Advitha without removing it. search counts from the top starting at 1, so Navika at the bottom is position 3. pop removes Advitha.

Example: Reversing a Word

A classic use of a stack is reversing things:

Reverse.java▶ Try it
import java.util.Stack;
 
public class Reverse {
    public static void main(String[] args) {
        String word = "Navika";
        Stack<Character> stack = new Stack<>();
        for (char c : word.toCharArray()) {
            stack.push(c);
        }
        StringBuilder reversed = new StringBuilder();
        while (!stack.empty()) {
            reversed.append(stack.pop());
        }
        System.out.println(reversed);
    }
}
Output
akivaN

Explanation: The letters are pushed in order N, a, v, i, k, a. Popping returns them in the opposite order, which builds the reversed word.

Use ArrayDeque Instead

Because Stack extends Vector, it is synchronized (slower) and also exposes list methods such as add(index, e) that break the stack idea. The Java documentation recommends the Deque interface instead:

DequeStack.java▶ Try it
import java.util.ArrayDeque;
import java.util.Deque;
 
public class DequeStack {
    public static void main(String[] args) {
        Deque<String> stack = new ArrayDeque<>();
        stack.push("Navika");
        stack.push("Srihitha");
        stack.push("Advitha");
        System.out.println("Stack: " + stack);
        System.out.println("Popped: " + stack.pop());
        System.out.println("Top now: " + stack.peek());
    }
}
Output
Stack: [Advitha, Srihitha, Navika]
Popped: Advitha
Top now: Srihitha

Explanation: ArrayDeque has the same push, pop and peek methods. Note that it prints the top first, the reverse of how Stack prints. It isn't synchronized, so it's faster.

Common Mistakes

Calling pop() without checking empty(). An empty Stack throws EmptyStackException.

Expecting search to return a 0-based index. It returns a 1-based distance from the top.

Using Stack in new code. Prefer ArrayDeque.

Practice

  1. Easy: Use a stack to print the numbers 1 to 5 in reverse order.
  2. Harder: Use an ArrayDeque as a stack to check whether a string of brackets such as "([]{})" is balanced.

Quick check: Stack

4 questions
1What order does a stack follow?
2Which method looks at the top without removing it?
3Which class does Stack extend?
4What does modern Java recommend for a stack?

Key Takeaways

Was this tutorial helpful?

Lesson 266 of 482