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.
Call stack
1
main()
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
- Bubble sort in Java, step by step
- Binary search in Java, step by step
- Java ArrayList visualizer
- Java linked list visualizer
- Java objects and references, visualized
- Java 2D array visualizer
Or open the Java visualizer and paste your own code.