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:
-
Base Case → Condition to stop recursion (prevents infinite loop).
-
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:
✅ 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:
✅ 4. Example 3: Sum of First N Natural Numbers
📌 Output:
✅ 5. Example 4: Reverse a String Using Recursion
📌 Output:
✅ 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).
