Java ProgramsRecursionFactorial Using Recursion

Factorial Using Recursion in Java

beginner·  Recursion  ·  Recursion

Problem

A tail-recursive call is one where the recursive call is the very last action a method performs — nothing is left to do with its result once it returns, unlike a call that still has to multiply its own return value afterward.

Given a number, compute its factorial using a tail-recursive helper that carries the running product forward.

Input
6
Output
6! = 720

Java Program

Java
public class FactorialTailRecursion { static long factorial(int n, long accumulator) { if (n == 0) return accumulator; // nothing left to do — hand back the running product return factorial(n - 1, accumulator * n); // multiply before recursing, not after } public static void main(String[] args) { int n = 6; System.out.println(n + "! = " + factorial(n, 1)); } }

Output

6! = 720

Core Logic

Passing the running product along as an extra parameter means each call can return that accumulator directly at the base case, with no pending multiplication left for any caller to finish.

How It Works
  1. 1factorial(n, accumulator) takes a second parameter that carries the product built up so far.
  2. 2The base case if (n == 0) return accumulator; simply hands back whatever total has already been accumulated.
  3. 3Every other call returns factorial(n - 1, accumulator * n) — the multiplication happens before the recursive call, not after it returns.
  4. 4The initial call factorial(n, 1) starts the accumulator at 1, the multiplicative identity.
For n = 6, the accumulator builds up across calls as 1, 6, 30, 120, 360, 720, and the base case simply returns that final 720.
💡

Key Point: Unlike the plain recursive version's n * factorial(n - 1), which still owes a multiplication once the smaller call returns, this call is the last thing the method does — that's what makes it tail-recursive.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: Java doesn't perform tail-call optimization, so despite being tail-recursive, this still pushes a new stack frame per call, just like plain recursion — the accumulator pattern changes when the multiplication happens, not how many frames pile up.

Key Concepts

tail recursionaccumulator parameterbase case

Related Programs