Home / Questions / What is recursion?
Explanatory Question

What is recursion?

👁 0 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Recursion in Java is a technique where a method calls itself to solve a problem. It helps break a complex problem into smaller parts.

Definition

Recursion means calling the same method repeatedly until a stopping condition is reached.

Important Parts of Recursion

1. Base Case

The base case is the condition that stops recursion.

2. Recursive Case

The recursive case is where the method calls itself with smaller input.

Syntax


returnType methodName(parameters) {
    if (condition) {
        return value;
    }
    return methodName(smallerInput);
}
  

Example: Factorial


public class RecursionExample {

    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(5));
    }
}
  

Step-by-Step Explanation

Step Process
factorial(5) 5 × factorial(4)
factorial(4) 4 × factorial(3)
factorial(3) 3 × factorial(2)
factorial(2) 2 × factorial(1)
factorial(1) Returns 1 (Base Case)

Advantages

  • Short and clean code
  • Easy to solve complex problems
  • Useful in algorithms

Disadvantages

  • Uses more memory
  • May cause StackOverflowError
  • Sometimes slower than loops

Conclusion

Recursion is a powerful concept in Java where a method calls itself until a base condition is met.