Recursion
Every recursive method needs a base case that stops further calls and at least one recursive call that reduces the problem. The base case handles the simplest input without recursion; it prevents infinite loops. The recursive call applies the same method to a smaller or simpler input. The following example computes the factorial, which is the product of all positive integers up to a given number:
public int factorial(int n) {
if (n <= 1) { // Base case: stops recursion
return 1;
}
return n * factorial(n - 1); // Recursive call: reduces the problem
}