Java Notes
Learn the Stack class in Java — LIFO principle, push, pop, peek, and why ArrayDeque is the modern preferred alternative for stack operations.
A Stack follows LIFO — Last In, First Out. The last element you put in is the first one you take out. Think of a stack of plates: you add to the top and remove from the top.
Java has a Stack class, but it is a legacy class from Java 1.0. For new code, use ArrayDeque as a stack. This lesson covers both.
The Stack Class — push, pop, peek
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
stack.push("Third")— Third goes on top. Stack is now [First, Second, Third] (top = Third).stack.peek()— returns "Third" without removing it.stack.pop()— removes and returns "Third".stack.search("First")— returns 2 (Second is at position 1 from top, First is at position 2).
Real Use Case: Checking Balanced Brackets
A stack is perfect for this — open brackets get pushed, close brackets check against the top.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Preferred Alternative: ArrayDeque as Stack
The Stack class is synchronized on every method — slow in single-threaded code. ArrayDeque is faster and the official recommendation.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
ArrayDeque.push() = addFirst(). ArrayDeque.pop() = removeFirst(). Behaviour identical to Stack, but faster.
| Stack | ArrayDeque | |
|---|---|---|
| Thread-safe | Yes (synchronized) | No |
| Performance | Slower | Faster |
| Recommendation | Legacy code only | New code |
| Can also be used as | Only stack/vector | Stack, Queue, Deque |
Common Mistake: Calling pop() on Empty Stack
Stack<String> stack = new Stack<>();
// stack.pop(); // EmptyStackException
// Safe pattern
if (!stack.empty()) {
String top = stack.pop();
}Always check empty() or isEmpty() before popping when the stack might be empty.
Practice Task
Task: Use a Stack<Integer> (or ArrayDeque<Integer>) to reverse an array. Push all elements onto the stack, then pop them into a new array. The popped order is the reverse.
Hint: Push elements in order 0 to n-1. Pop n times into positions 0 to n-1 of the result array.
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: Pushing 1,2,3,4,5 puts 5 on top. Popping gives 5,4,3,2,1. The stack's LIFO property does the reversal automatically — no index math needed.
Continue the lesson path