Recursion in Java.

Introduction: In Java, recursion is nothing but a programming technique where a method/ function calls itself. Recursive methods have a base case, which is the condition that stops the recursion, and a recursive case, which is the logic that calls the method again with a modified version of the input.

Here is an example of a simple recursive method in Java that calculates the factorial of a number:

public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } }

In this example, the base case is when the input is 0, and the recursive case is when the input is greater than 0. The method calls itself with the input decremented by 1 until the base case is reached.

What happen when the base condition is not defined properly? If the base case is not reached or not defined, then the stack overflow problem may arise. Base condition is simple if condition.

Types of Recursion:

  1. Direct Recursion.
  2. Indirect Recursion.

Memory allocation while different function calls in Recursion? When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for the called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call. When the base case is reached, the function returns its value to the function by whom it is called and memory is de-allocated and the process continues.

How to solve problem using Recursion?

  1. Practice lot of problems, start with simple one.
  2. Try to break down problem into smaller version. E.g. fibonachi series, binary search.

Formula: f(n) = f(n - 1) + f(n - 2).

Recursion can be a powerful tool for solving problems, but it can also lead to infinite loops or stack overflow errors if not used carefully.