Stack in Java
Explore Java's Stack class, the LIFO data structure, its legacy design, and why ArrayDeque is the modern replacement for stack operations.
A stack is a Last-In-First-Out (LIFO) data structure: the last element pushed onto the stack is the first one popped off. Java provides java.util.Stack<E>, a class that extends Vector and adds five stack-specific methods. Because Stack inherits from Vector, it also inherits all of Vector's synchronised methods and its legacy design. The Java documentation explicitly recommends using ArrayDeque instead of Stack for LIFO stacks in new code. Understanding both Stack and its modern replacement is important for interviews.
The Stack Class
Stack<E> extends Vector<E> and adds:
| Method | Description |
|---|---|
E push(E item) |
Pushes item onto the top of the stack and returns it. |
E pop() |
Removes and returns the top element. Throws EmptyStackException if empty. |
E peek() |
Returns the top element without removing it. Throws EmptyStackException if empty. |
boolean empty() |
Returns true if the stack has no elements. |
int search(Object o) |
Returns the 1-based position from the top of the stack, or -1 if not found. |
Because Stack extends Vector, it also exposes all of Vector's index-based methods (get, add, remove, set). This means callers can insert or remove elements at arbitrary positions — violating the stack contract. This design flaw is one of the reasons Stack is considered legacy.
Example 1: Java's Stack Class
import java.util.Stack;
public class LegacyStack {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("first");
stack.push("second");
stack.push("third");
System.out.println("Peek: " + stack.peek()); // third (not removed)
System.out.println("Pop: " + stack.pop()); // third
System.out.println("Pop: " + stack.pop()); // second
System.out.println("Size: " + stack.size()); // 1
System.out.println("Search 'first': " + stack.search("first")); // 1 (top = 1)
System.out.println("Empty: " + stack.empty()); // false
}
}
Example 2: ArrayDeque as a Stack (Preferred)
import java.util.ArrayDeque;
import java.util.Deque;
public class ModernStack {
public static void main(String[] args) {
// ArrayDeque used as a LIFO stack — the preferred approach
Deque<String> stack = new ArrayDeque<>();
stack.push("first"); // addFirst
stack.push("second");
stack.push("third");
System.out.println("Peek: " + stack.peek()); // third
System.out.println("Pop: " + stack.pop()); // third
System.out.println("Pop: " + stack.pop()); // second
System.out.println("Size: " + stack.size()); // 1
// Practical use: checking balanced parentheses
System.out.println(isBalanced("({[]})")); // true
System.out.println(isBalanced("({[}])")); // false
}
static boolean isBalanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
}
Stack vs. ArrayDeque as a Stack
| Feature | Stack |
ArrayDeque (as stack) |
|---|---|---|
| Backed by | Vector (synchronised) |
Circular resizable array |
| Thread safety | Synchronised (per-method) | Not synchronised |
| Performance | Slower (lock overhead) | Faster |
| Null elements | Allowed | Not allowed |
| Can break LIFO | Yes (index methods from Vector) | No (Deque API only) |
| Recommended for new code | No | Yes |
| LIFO methods | push, pop, peek, empty |
push, pop, peek, isEmpty |
Common Mistakes
- Using
java.util.Stackin new code. It is legacy, inheritsVector's synchronised overhead, and exposes index-based methods that break the stack abstraction. UseArrayDequeinstead. - Calling
pop()orpeek()on an emptyStack. These throwEmptyStackException. Always checkempty()(orisEmpty()onDeque) before calling them. - Confusing
Deque.push/popdirection. On aDequeused as a stack,push(e)callsaddFirst(e)andpop()callsremoveFirst(). The head of the deque is the top of the stack. - Relying on
Stack.search(). Thesearchmethod returns a 1-based position counting from the top — this unusual convention is easy to misuse. There is no equivalent onArrayDeque; iterate manually if needed. - Using
Stackin a multi-threaded context and assuming safety. Even though all methods are synchronised, compound check-then-act operations are still racy unless synchronised externally, the same limitationVectorhas.
Best Practices
- Use
Deque<E> stack = new ArrayDeque<>()for all new stack code. - Declare the type as
Deque<E>, notArrayDeque<E>, in variable and parameter declarations. - For thread-safe stacks, use
ConcurrentLinkedDequeor aLinkedBlockingDeque. - Always check
isEmpty()before callingpop()orpeek()to avoidNoSuchElementException. - When solving algorithm problems that need a stack (DFS, expression evaluation, bracket matching),
ArrayDequeis the idiomatic Java choice.
Interview Questions
1. What is a stack and how does it work?
A stack is a LIFO (Last-In-First-Out) data structure. Elements are added (pushed) and removed (popped) from the same end, called the top. Common operations are push (add to top), pop (remove and return top), and peek (return top without removing). Classic applications include undo functionality, call-stack simulation, DFS traversal, and expression parsing.
2. What class should you use for a stack in modern Java?
ArrayDeque<E> used via the Deque<E> interface: Deque<E> stack = new ArrayDeque<>(). The push, pop, and peek methods map to addFirst, removeFirst, and peekFirst respectively. ArrayDeque is faster than Stack because it is not synchronised and uses a contiguous backing array.
3. Why is java.util.Stack considered a poor design?
Stack extends Vector, which means it inherits all of Vector's synchronized index-based methods (get, add(i, e), remove(i) etc.). This allows callers to insert and remove elements at arbitrary positions, violating the LIFO contract. It also carries Vector's synchronisation overhead even in single-threaded contexts.
4. What is the difference between pop() and peek()?
pop() removes the top element and returns it. peek() returns the top element without removing it. Both throw EmptyStackException (on Stack) or NoSuchElementException (on Deque) if the stack is empty.
5. How would you implement a stack using two queues?
Use two Queue instances. For push: enqueue to queue1. For pop: move all elements from queue1 to queue2 except the last one, return the last element, then swap the names of queue1 and queue2. This gives O(n) pop and O(1) push. Alternatively, O(1) pop and O(n) push by always moving on push.
6. How would you implement a min-stack that returns the minimum element in O(1)?
Maintain two stacks: the main stack and an auxiliary minStack. On push(x), push x onto the main stack and push min(x, minStack.peek()) onto minStack. On pop(), pop from both stacks. getMin() returns minStack.peek(). All operations are O(1).
Deque<Integer> main = new ArrayDeque<>();
Deque<Integer> mins = new ArrayDeque<>();
void push(int x) {
main.push(x);
mins.push(mins.isEmpty() ? x : Math.min(x, mins.peek()));
}
void pop() { main.pop(); mins.pop(); }
int getMin() { return mins.peek(); }
7. Is ArrayDeque null-safe for stack operations?
No. ArrayDeque does not permit null elements. Calling push(null) throws NullPointerException. If you need null elements in a stack, use a LinkedList via the Deque interface — but this is rarely needed in practice.
Summary
- A stack is a LIFO structure;
pushadds to the top,popremoves from the top. java.util.Stackis a legacy class extendingVector; it is synchronised and exposes index-based methods that break the LIFO contract.- Use
ArrayDequevia theDequeinterface for all new stack code. - Always guard
pop()andpeek()with anisEmpty()check to avoid exceptions. - The min-stack problem (O(1) minimum retrieval) is a classic interview question that builds on basic stack knowledge.
Continue Learning
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.