SrcForge

Lesson 31

Recursion

Recursion is a method calling itself until a base case stops it. Used for factorials, trees and divide-and-conquer problems.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Recursion is a method calling itself until a base case is met.

Key Terms

  • Recursion: A method calling itself to solve a problem.
  • Recursive Method: A method containing a call to itself.
  • Base Case: Condition that stops recursive calls.
  • Recursive Case: Where the method calls itself with modified input.

How Recursion Works

  1. Check base case stopping condition.
  2. Perform a task.
  3. Call itself with smaller input.
  4. Continue until base case is reached.

Example 1: Sum of Numbers

package Recursion;

public class recursion {
    public static void main(String[] args) {
        int result = sum(10);
        System.out.println(result);
    }

    public static int sum(int k) {
        if (k > 0) {
            return k + sum(k - 1);
        } else {
            return 0;
        }
    }
}

Output

55

Example 2: Factorial Using Recursion

package Recursion;

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

    public static long multiplyNumbers(int num) {
        if (num >= 1)
            return num * multiplyNumbers(num - 1);
        else
            return 1;
    }
}

Output

Factorial of 6 = 720

Advantages

  • Shorter, cleaner code for repetitive patterns.
  • Breaks complex problems into smaller tasks.
  • Ideal for trees, graphs and hierarchical data.

Disadvantages

  • Each call consumes call stack memory.
  • Slower than iterative solutions.
  • Missing base case causes stack overflow.

FAQ

1. What is recursion in Java?

A method calling itself until a base condition stops it.

2. What is the base case for?

Stops recursive calls. Prevents infinite recursion.

3. When should recursion be used?

Factorial, tree traversal, divide-and-conquer algorithms.

Recursion is a method calling itself.
Base case stops the recursion.
Missing base case causes stack overflow.
Each call uses call stack memory.
Good for trees, graphs, factorial.
Loops may be faster for simple tasks.
Recursive case must approach base case.

Where Java is used

Java in real-world development

Base Case

Stopping condition. Required in every recursive method. Prevents infinite loops.

Recursive Case

Method calls itself with smaller input. Moves toward the base case.

Sum Example

sum(10) calls sum(9), then sum(8)... until sum(0) returns 0. Total: 55.

Factorial Example

6! = 6 × 5 × 4 × 3 × 2 × 1 = 720. Base case returns 1.

Stack Overflow Risk

No base case means infinite calls. Call stack fills up and crashes.

When to Use

Tree traversal, factorial, Fibonacci, divide-and-conquer. Use loops for simple tasks.

Prev: Object ClassBack to hub