Recursive Factorial Function in Java- Complete Guide
What Is Factorial, Anyway?
Factorial is simple math. The factorial of a number n (written as n!) is the product of all positive integers from 1 to n.
So:
- 5! = 5 ร 4 ร 3 ร 2 ร 1 = 120
- 3! = 3 ร 2 ร 1 = 6
- 0! = 1 (this is a rule, not a mistake)
That's it. No tricks. Now here's the problem: calculating factorials by hand gets old fast. That's where code comes in, and specifically, recursion.
The Recursive Factorial Function in Java
Here's the complete code. Memorize it. This is the foundation of everything else.
public class Factorial {
public static long factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
}
}
Two methods. One recursive call. That's the entire thing.
How Recursion Actually Works
When you call factorial(5), here's what happens step by step:
- factorial(5) needs factorial(4)
- factorial(4) needs factorial(3)
- factorial(3) needs factorial(2)
- factorial(2) needs factorial(1)
- factorial(1) returns 1 โ this is the base case
- factorial(2) calculates 2 ร 1 = 2
- factorial(3) calculates 3 ร 2 = 6
- factorial(4) calculates 4 ร 6 = 24
- factorial(5) calculates 5 ร 24 = 120
Each call waits for the next one to finish. The call stack builds up, then unwinds with actual values. This is the recursion pattern: build, then unwind.
Base Case: The Non-Negotiable Part
The base case stops the recursion. Without it, you get a StackOverflowError. That's not a bugโit's the program crashing because it ran out of memory.
Your base case is if (n <= 1) return 1;
That's it. Every recursive function needs this. Period.
Why n <= 1 and Not n == 1?
Because 0! = 1. If someone calls factorial(0), the function returns 1 immediately. Without the <= check, you'd try to compute 0 ร factorial(-1), which leads to infinite recursion.
Iterative vs Recursive: The Comparison
Recursion looks elegant. But it's not always the best choice. Here's the breakdown:
| Aspect | Recursive | Iterative |
|---|---|---|
| Code length | Shorter | Longer |
| Memory usage | High (stack frames) | Low (constant) |
| Speed | Slower (function calls) | Faster |
| Readability | Cleaner for math problems | More complex for factorial |
| Stack overflow risk | Yes, with large n | No |
The iterative version:
public static long factorialIterative(int n) {
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
For factorial, the iterative version is faster and uses less memory. Recursion is still worth learning because the pattern applies everywhere else.
Common Mistakes and How to Fix Them
Mistake 1: Forgetting the Base Case
If you remove the if (n <= 1) check, your program crashes. There's no way around this. The base case is not optional.
Mistake 2: Using int for Large Numbers
Factorials grow fast. 12! exceeds int's max value (2,147,483,647). Use long at minimum. For anything serious, use BigInteger.
import java.math.BigInteger;
public static BigInteger factorialBig(int n) {
if (n <= 1) return BigInteger.ONE;
return BigInteger.valueOf(n).multiply(factorialBig(n - 1));
}
Mistake 3: Negative Input
Factorial isn't defined for negative numbers. Your function will either crash or return wrong values. Handle this explicitly if user input is involved.
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Negative numbers not allowed");
}
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Getting Started: Your First Recursive Factorial
Step 1: Create a file called Factorial.java
Step 2: Paste this code:
import java.util.Scanner;
public class Factorial {
public static long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
System.out.println(num + "! = " + factorial(num));
scanner.close();
}
}
Step 3: Compile and run. That's all. You now have a working factorial calculator.
When to Use Recursion (And When Not To)
Use recursion when:
- You're working with tree or graph traversal
- The problem naturally divides into smaller identical problems
- Code clarity matters more than raw performance
- You're writing algorithms for sorting, searching, or combinatorial problems
Skip recursion when:
- You're dealing with tight loops where performance matters
- Stack depth could exceed a few thousand calls
- You're on memory-constrained systems
Factorial is a teaching tool. Real-world factorial calculations almost always use iteration. But the recursive thinking? That carries over to every complex algorithm you'll write.