Stacks
Lesson 11 of 20Push, pop and peek through an ArrayDeque — then watch brackets balance and the next-greater scan unfold.
Meet the stack
A stack is a pile where only the top is ever touched. Whatever went in last comes out first — that rule powers undo history, bracket matching and every method call the JVM makes.
LIFO rule
Last In, First Out. Push 12 then 7, and the first pop hands you back 7 — the newest value always leaves first.
Three O(1) moves
push places a value on top, pop removes it, peek just reads it. None of them ever shift the other elements.
The Java toolbox
Use ArrayDeque from java.util: push, pop and peek map to addFirst, removeFirst and peekFirst. The legacy Stack class still works but ArrayDeque is faster.
Where you meet it
Ctrl+Z, the browser back button, matching brackets in your IDE and the JVM call stack are all stacks doing their thing.
Overflow is literal
Push onto a full array-backed stack and you get the error that gave this website its name: stack overflow.
Push & pop live
One slot of contact — watch values stack up and leave in reverse order.
An empty ArrayDeque used as a stack — nothing in it yet.
Bracket checker flow
The classic interview question: is "{[()]}" balanced? An ArrayDeque decides.
Walkthrough
An array-backed stack with push and pop — plus the next-greater scan on an ArrayDeque.
1public class ArrayStack {2static int[] stk = new int[5];3static int top = -1;45static void push(int v) {6if (top == 4) { System.out.println("full"); return; }7stk[++top] = v;8}910static int pop() {11if (top == -1) return -1;12return stk[top--];13}1415public static void main(String[] args) {16push(12);17push(7);18push(21);19System.out.println(pop());20System.out.println(pop());21}22}
stk reserves 5 int slots — the body of the stack.
Stack in array memory
The array under the stack — pushes write slots in place, pops just move top back.
Predict the output
ArrayDeque push/pop/peek — trace the head of the deque by hand.
1import java.util.ArrayDeque;2import java.util.Deque;34public class Predict {5public static void main(String[] args) {6Deque<Integer> st = new ArrayDeque<>();7st.push(4);8st.push(9);9st.push(2);10System.out.println(st.pop());11System.out.println(st.peek());12System.out.println(st.pop());13System.out.println(st.size());14}15}
Hint: ArrayDeque push adds at the head and pop removes the head — the last value pushed leaves first. peek only reads.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
A stack touches only the top: push, pop and peek are all O(1).
LIFO order — the last value pushed is the first one popped.
In Java prefer ArrayDeque over the legacy Stack class: push, pop, peek.
Check isEmpty() before pop or peek — empty containers throw.
Balanced brackets and next-greater-element are the two interview classics.
The JVM call stack pushes a frame per method call — recursion depth lives here.