Codiqo

Learn Java · lesson 52 of 61 · about 8 minutes

Tracing and Fixing Recursion

Follow every call step by step, and spot recursion that never stops.

What you'll learn

  • Trace the order of recursive calls
  • Explain what the call stack is
  • Fix a missing or unreachable base case

The lock-up walk

Last thing at night, the manager walks through the building switching the lights off: into the foyer, into screen 1, into the projection room, and then back out the same way, the other way round. The desk gets that for free from the call stack. walkIn prints Into foyer before its recursive call, on the way in, and Out of foyer after it, on the way back out, so the rooms come out in the reverse of the order they went in. The manager types up to 6 rooms until done.

The call stack

Every call gets its own copy of its parameters and local variables, in a stack frame. When a method calls itself, the first call waits while the new one runs.

When the base case returns, the calls finish one by one, newest first. Code after the recursive call runs on the way back out.

In and out

public class Main {
    static void dive(int n) {
        if (n == 0) {
            System.out.println("bottom");
            return;
        }
        System.out.println("going down " + n);
        dive(n - 1);
        System.out.println("coming up " + n);
    }

    public static void main(String[] args) {
        dive(2);
    }
}

Output

going down 2
going down 1
bottom
coming up 1
coming up 2

Each frame remembers its own room

walkIn takes the index i of the room it's going into. When it calls itself with i + 1, its own i stays the same in its own frame, so the Out of line after the call prints the room it went into, not the next one.

StackOverflowError

If the base case is missing, or the calls never reach it, frames pile up until the stack runs out and Java throws a StackOverflowError. The stack trace shows the same method over and over. Check that every path makes the problem smaller and that the base case catches the smallest one.

Catching a runaway

public class Main {
    static int forever(int n) {
        return forever(n + 1);
    }

    public static void main(String[] args) {
        try {
            forever(1);
        } catch (StackOverflowError e) {
            System.out.println("Stack overflow!");
        }
    }
}

Output

Stack overflow!

Tip

You'd never catch StackOverflowError in a real program; the fix is a correct base case. It's caught here only to show what happens.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.