Stacks

Lesson 11 of 20

Push, pop and peek through an ArrayDeque — then watch brackets balance and the next-greater scan unfold.

The big picture

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.