Where are stacks used, and why is a stack the natural structure for method calls?
Directly for browser history, undo in an editor and the call stack of a running program; indirectly as a helper structure inside other algorithms and data structures. Method calls use a stack because the most recently called method is always the first to return.
Direct applications:
- Browser history. Each visited page is pushed; "back" pops to the previous one.
- Undo in an editor. Each edit is pushed; undo pops the most recent one first.
- Run configurations in an IDE, with the most recently used on top.
- Method calls in the runtime. When
a()callsb()which callsc(),cmust finish beforebcan continue, andbbeforea. Returns happen in exactly the reverse order of calls, which is LIFO. The runtime pushes a stack frame (parameters, local variables, return address) per call and pops it on return.
That last point is what makes recursion work: each recursive call gets its own frame on the call stack, so each level has its own copy of the local variables. It is also why infinite recursion ends in a StackOverflowError: the stack has a fixed size and runs out of room.
Indirect applications: stacks serve as building blocks inside other algorithms (evaluating arithmetic expressions, checking matching brackets, depth-first search) and inside other data structures.
Go deeper:
Call stack — stack frames, return addresses, and how recursion uses them.
Reverse Polish notation — the classic indirect use: evaluating expressions with a stack.