Course contentsShow
← Java
Lesson 231 of 2,8705. Methods and Function CallsFree lesson

Tail Recursion: Optimizable Recursive Calls

A tail-recursive call is the last operation in a method; Java doesn't optimize tail recursion (unlike some languages).

Tail Recursion: Optimizable Recursive Calls

What you'll learn: You'll understand what tail recursion is and why it matters (even though Java doesn't optimize it).

What Is Tail Recursion?

A tail-recursive call happens when the recursive method call is the very last operation the method performs—nothing else happens after the recursive call returns. In other words, the method doesn't need to "remember" anything or do additional work after the recursive call completes.

Non-tail recursive example (factorial):

public static int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);  // ❌ Not tail-recursive!
}

Why not? Because after factorial(n - 1) returns, the method still has work to do: multiply the result by n.

Tail-recursive version (factorial with accumulator):

public static int factorialTail(int n, int accumulator) {
    if (n <= 1) return accumulator;
    return factorialTail(n - 1, n * accumulator);  // ✅ Tail-recursive!
}

Here, the recursive call is the last thing executed. The multiplication happens before the call, not after.

Why Does This Matter?

In some programming languages (like Scala or Scheme), compilers optimize tail-recursive calls into loops, preventing stack overflow errors. Java does not perform this optimization, so tail recursion doesn't save stack space in Java. Both versions above will eventually cause a StackOverflowError with deep recursion.

However, understanding tail recursion helps you write clearer code and prepares you for languages that do optimize it.

Key Takeaway: Tail recursion occurs when the recursive call is the absolute last operation in a method; Java doesn't optimize tail-recursive calls like some other languages do, so they still consume stack space just like regular recursion.