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.

returnType methodName(parameters) {
if (baseCondition) {
return value;
} else {
return methodName(modifiedParameters); // recursive call
}
}

✅ 2. Example 1: Factorial of a Number

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

public class Main {
static int factorial(int n) {
if (n == 0 || n == 1) { // base case
return 1;
} else {
return n * factorial(n - 1); // recursive case
}
}

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

📌 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

public class Main {
static int fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {
int n = 10;
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}

📌 Output:

0 1 1 2 3 5 8 13 21 34

✅ 4. Example 3: Sum of First N Natural Numbers

public class Main {
static int sum(int n) {
if (n == 1) return 1; // base case
return n + sum(n - 1); // recursive case
}

public static void main(String[] args) {
int n = 5;
System.out.println("Sum of first " + n + " numbers = " + sum(n));
}
}

📌 Output:

Sum of first 5 numbers = 15

✅ 5. Example 4: Reverse a String Using Recursion

public class Main {
static String reverse(String str) {
if (str.isEmpty()) return ""; // base case
return reverse(str.substring(1)) + str.charAt(0);
}

public static void main(String[] args) {
String text = "Java";
System.out.println("Reversed: " + reverse(text));
}
}

📌 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).

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *