Java Recursion

Java Recursion

Recursion in Java is a programming technique where a method calls itself to solve a problem. It is useful for problems that can be broken down into smaller, similar subproblems.


1. Structure of a Recursive Method

A recursive method generally has two parts:

  1. Base Case → Condition to stop recursion (prevents infinite loop).

  2. Recursive Case → Part where the method calls itself.



 


2. Example 1: Factorial of a Number

The factorial of n is n! = n * (n-1) * ... * 1.



 

📌 Output:

Factorial of 5 = 120

3. Example 2: Fibonacci Series

Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8…
F(n) = F(n-1) + F(n-2), F(0)=0, F(1)=1


 

📌 Output:

0 1 1 2 3 5 8 13 21 34

4. Example 3: Sum of First N Natural Numbers


 

📌 Output:

Sum of first 5 numbers = 15

5. Example 4: Reverse a String Using Recursion


 

📌 Output:

Reversed: avaJ

6. Key Points About Recursion

  • Always define a base case to stop recursion.

  • Each recursive call consumes stack memory, deep recursion may cause StackOverflowError.

  • Recursion is often elegant, but loops may be more memory-efficient.

  • Useful in factorials, Fibonacci series, tree traversal, sorting algorithms (QuickSort, MergeSort).

You may also like...