Recursion in Java

Recursion in Java is a technique where a method calls itself to solve a problem. It can be a powerful tool for solving problems that can be broken down into smaller, similar problems. Here's a simple explanation for beginners:

Key Concepts:

  1. Base Case: This is the condition that stops the recursion. Without a base case, the method would call itself indefinitely, causing a stack overflow error.
  2. Recursive Case: This is where the method calls itself with a different argument, moving closer to the base case with each call.

Example:

Let's look at a classic example: calculating the factorial of a number.

Factorial Definition:

The factorial of a number n (denoted as n!) is the product of all positive integers up to n

For example 5!=5×4×3×2×1=120

Recursive Definition:

  • The factorial of 0 is 1. This is the base case.
  • The factorial of is n×(n1)!. This is the recursive case.

Java Code:

public class Factorial {

// Method to calculate factorial using recursion
public static int factorial(int n) {
// Base case: if n is 0, return 1
if (n == 0) {
return 1;
}
// Recursive case: n * factorial of (n-1)
return n * factorial(n - 1);
}

public static void main(String[] args) {
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is " + result);
}
}

How It Works:

  1. Initial Call: factorial(5)
  2. First Recursive Call: 5 * factorial(4)
  3. Second Recursive Call: 5 * (4 * factorial(3))
  4. Third Recursive Call: 5 * (4 * (3 * factorial(2)))
  5. Fourth Recursive Call: 5 * (4 * (3 * (2 * factorial(1))))
  6. Fifth Recursive Call: 5 * (4 * (3 * (2 * (1 * factorial(0)))))
  7. Base Case Reached: factorial(0) returns 1

The final result is 120, which is the factorial of 5.

Comments