solulubeta
Sign in
Recursion & Memo / See it, then write it
01.02 · Lesson

How Java Runs Recursion

Every call is a new copy with its own variables. The caller waits and then continues. Code before the call runs on the way down, code after it runs on the way back up.

10 min 2 videos Quiz Free
Re 1. Introduction to Recursion | Recursion Tree | Stack Space · take U forward
Recursion in Java Full Tutorial - How to Create Recursive Methods · Coding with John

Each call is a new copy

When a method calls itself, Java makes a new copy of it (called a frame) with its own variables and puts it on top of the call stack. The calling copy pauses on that line. When the new copy returns, the paused copy continues from where it stopped.

static int fact(int n) {
    if (n == 0) return 1;          // base case
    int smaller = fact(n - 1);     // pause here until the answer comes back
    return n * smaller;
}

Watch three things:

  1. Going down, every copy stops at fact(n - 1).
  2. Only fact(0) answers without calling anyone.
  3. Coming back up, each copy multiplies by its own n.

Code before the call vs after the call

static void show(int n) {
    if (n == 0) return;
    System.out.println("down " + n);   // before the call
    show(n - 1);
    System.out.println("up " + n);     // after the call
}
  • Code before the call runs on the way down.
  • Code after the call runs on the way back up, in reverse order.

Guess the output of show(3), then check:

The answer is down 3, down 2, down 1, up 1, up 2, up 3. If you expected up 3 first, you were thinking “the call is a jump”. It isn’t: show(3) is a separate copy that still has n = 3 when it continues.

Tracing on paper

For “what does this print” questions, write one line per call and indent by depth:

fact(3)
  fact(2)
    fact(1)
      fact(0) -> 1
    fact(1) = 1 * 1 = 1
  fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6

The indentation is the call stack. You can do the same in Java when debugging: print with " ".repeat(depth).

StackOverflowError

  • No base case, or it’s never reached: the calls never stop.
  • Too deep: Java handles a few thousand nested calls. On this site, Java runs in your browser, so stay under about 5,000.

For very deep inputs, use a loop or a table instead (chapter 3).

Remember

  • New call = new copy with its own variables.
  • The caller waits, then continues.
  • Before the call = on the way down. After the call = on the way up.

Check yourself

Question 1 of 3

When fact(3) calls fact(2), what happens to fact(3)?

Question 2 of 3

What does this print for show(2)?

void show(int n) {
    if (n == 0) return;
    show(n - 1);
    System.out.print(n + " ");
}
Question 3 of 3

Your recursion throws StackOverflowError. The most likely reason?

Mark this as done when you are finished.

Item 2 of 44 · updated 2026-10-13