+91 81900 98289

Java Recursion

A recursive method calls itself with a smaller problem and must have a base case that stops. Without a base case the calls never end, and the program fails with StackOverflowError.

Factorial and a folder walk are natural recursive problems. A plain count from 1 to 10 is clearer as a loop. Use recursion when the data itself is nested.

Example

factorial(4) calls factorial(3), which calls factorial(2), which calls factorial(1). The base case returns 1, then each caller multiplies.

public class Fact { static int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } public static void main(String[] args) { System.out.println(factorial(4)); } }
4 * 3 * 2 * 1 is 24. Keep the first recursive examples on small inputs. A deep chain uses one stack frame per call.