2 · Control Flow & Methods · lesson 11 of 41

Recursion

A method that calls itself — and the stack frames it creates.

Java
static long factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
WATCH OUT
Each call pushes a new frame on the stack — too much recursion throws StackOverflowError.
Loading 3D scene…
Key takeaways
  • ✓Every recursive call needs a base case.
  • ✓Watch the stack grow in the 3D visualization for factorial(5).