Java recursion visualizer

Recursion is hard to picture because every call is paused while the next one runs. Step through factorial below and the call stack shows each paused call with its own copy of n, until the base case lets them finish one by one.

Source

line 1
Line that just executed Next line to execute
Sign in to share

Call stack

1
main()
line 1
Step 1/1

What to watch

  • Each call to factorial adds a new frame to the call stack, and each frame keeps its own value of n.
  • Nothing multiplies until n reaches 1. That is the base case, and it is the first call to return.
  • Every frame then finishes in reverse order, multiplying its n by the value the call above it returned.

Try changing it

  • Remove the base case and see what happens to the stack.
  • Rewrite it as fibonacci and count how many frames appear.

Edit the code above and press Visualize to see your version run.

More Java examples

Or open the Java visualizer and paste your own code.