r/learnjava • • Feb 08 '21

Help me understand recursion, please!

public static long method(long a, long b) {
    if (b == 0) {
        return b;
    }
    return a + method(a, b - 1);
}

So this apparently resolves to essentially a * b. I really don't understand this. The base case only ever returns b when b is zero, so in my flawed logic it's always a * 0 = 0.

51 Upvotes

15 comments sorted by

View all comments

22

u/spicycurry55 Feb 08 '21

The base case returns zero, yes, but it only returns it to the one place it’s called.

So if you call:

method(2, 1);

It resolves to:

method(2, 1) —> 2 + method(2, 0) —> 2 + 0 —> 2

You’re adding “a” to the recursive call, so even though the base case will return zero, it’s adding a zero, not multiplying it