Java Recursion - Recursive Methods with Complete Examples

⏱️ 9 min read • Beginner Level • Lesson 36

Lesson 36 of 124 of Java Tutorial

Recursion in Java is a programming technique where a method calls itself to solve a problem. A recursive method keeps calling itself until a stopping condition is reached.

Before learning recursion, you should understand Java Methods, Java Method Parameters, and Java Method Overloading.


What is Recursion in Java?

Recursion is a technique where a method solves a problem by calling itself again with a smaller or simpler input. This continues until the problem reaches a condition where no more recursive call is needed.

Simple Meaning: Recursion means a method repeats itself by calling itself. It must know when to stop.
RecursionBasicSyntax.java
returnType methodName(parameters) {
    if (baseCondition) {
        return value;
    }

    return methodName(smallerInput);
}

Real-World Examples of Recursion

Recursion is commonly used when a problem can be divided into smaller versions of the same problem.

Common Uses of Recursion:
  • Calculating factorials
  • Generating Fibonacci numbers
  • Traversing folders and files
  • Tree and graph processing
  • Backtracking algorithms
  • Directory searching systems
Example: When you open a folder that contains subfolders, each subfolder may contain more subfolders. This hierarchical structure is naturally solved using recursion.

How Recursion Works in Java

Every recursive call is stored in memory as a separate method call. Java uses the call stack to keep track of these method calls. When the base condition is reached, the methods start returning back one by one.

  1. The method is called with an input value.
  2. The method checks the base condition.
  3. If the base condition is false, the method calls itself with a smaller input.
  4. This process continues until the base condition becomes true.
  5. After that, all pending method calls return one by one.
Java Recursion Flowchart

Base Case and Recursive Case

A recursive method usually has two important parts: base case and recursive case.

Part Meaning
Base Case The stopping condition that prevents infinite recursion.
Recursive Case The part where the method calls itself with a smaller or simpler input.
Important: Without a base case, recursion may continue forever and cause a StackOverflowError.

Simple Recursion Example

In this example, the method prints numbers from 1 to 5 using recursion.

SimpleRecursionExample.java
Copy Try Download
public class SimpleRecursionExample {
    static void printNumbers(int number) {
        if (number > 5) {
            return;
        }

        System.out.println(number);
        printNumbers(number + 1);
    }

    public static void main(String[] args) {
        printNumbers(1);
    }
}

Output:

1
2
3
4
5

Code Explanation

  1. printNumbers(1) starts the recursive process.
  2. The condition number > 5 is the base case.
  3. If the number is not greater than 5, it is printed.
  4. printNumbers(number + 1) calls the same method with the next number.
  5. When number becomes 6, the method returns and recursion stops.

Factorial using Recursion in Java

Factorial of a number means multiplying that number by all positive numbers below it. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

FactorialRecursion.java
Copy Try Download
public class FactorialRecursion {
    static int factorial(int number) {
        if (number <= 1) {
            return 1;
        }

        return number * factorial(number - 1);
    }

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

Output:

Factorial: 120

Code Explanation

  1. factorial(5) is called from the main() method.
  2. The base case is number == 1. When number becomes 1, the method returns 1.
  3. The recursive case is number * factorial(number - 1).
  4. The calls become 5 * factorial(4), then 4 * factorial(3), and so on.
  5. Finally, Java calculates 5 * 4 * 3 * 2 * 1, which gives 120.

Sum of Natural Numbers using Recursion

We can use recursion to calculate the sum of natural numbers up to a given number. For example, sum up to 5 is 5 + 4 + 3 + 2 + 1 = 15.

SumNaturalNumbers.java
Copy Try Download
public class SumNaturalNumbers {
    static int sum(int number) {
        if (number == 0) {
            return 0;
        }

        return number + sum(number - 1);
    }

    public static void main(String[] args) {
        System.out.println("Sum: " + sum(5));
    }
}

Output:

Sum: 15

Code Explanation

  1. sum(5) starts the recursive calculation.
  2. The base case is number == 0, which returns 0.
  3. The recursive case is number + sum(number - 1).
  4. The calculation becomes 5 + 4 + 3 + 2 + 1 + 0.
  5. The final result is 15.

Fibonacci Series using Recursion

In the Fibonacci series, each number is the sum of the previous two numbers. The series starts with 0 and 1.

FibonacciRecursion.java
Copy Try Download
public class FibonacciRecursion {
    static int fibonacci(int number) {
        if (number == 0) {
            return 0;
        }

        if (number == 1) {
            return 1;
        }

        return fibonacci(number - 1) + fibonacci(number - 2);
    }

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

Output:

0 1 1 2 3 5 8

Code Explanation

  1. The method fibonacci() returns the Fibonacci number at a given position.
  2. The base cases are number == 0 and number == 1.
  3. For other numbers, the method returns fibonacci(number - 1) + fibonacci(number - 2).
  4. The loop calls fibonacci(i) for values from 0 to 6.
  5. The output displays the first seven Fibonacci numbers.
Note: Recursive Fibonacci is simple to understand but can be slow for large numbers because it repeats many calculations.

Print Numbers in Reverse using Recursion

Recursion can also be used to print numbers in reverse order.

ReverseNumbersRecursion.java
Copy Try Download
public class ReverseNumbersRecursion {
    static void printReverse(int number) {
        if (number == 0) {
            return;
        }

        System.out.println(number);
        printReverse(number - 1);
    }

    public static void main(String[] args) {
        printReverse(5);
    }
}

Output:

5
4
3
2
1

Code Explanation

  1. printReverse(5) starts printing from 5.
  2. If number == 0, the method stops.
  3. Each call prints the current number first.
  4. Then it calls itself with number - 1.
  5. This prints values from 5 down to 1.

Stack Overflow in Recursion

If a recursive method does not stop, it keeps adding method calls to the call stack. Eventually, the stack becomes full and Java throws a StackOverflowError.

InfiniteRecursion.java
public class InfiniteRecursion {
    static void callAgain() {
        System.out.println("Calling...");
        callAgain(); // no base case
    }

    public static void main(String[] args) {
        callAgain();
    }
}
Warning: Do not run infinite recursion examples in production code. Always write a clear base case.

Code Explanation

  1. callAgain() prints a message.
  2. Then it calls itself again.
  3. There is no base condition to stop recursion.
  4. The method keeps calling itself until the call stack becomes full.
  5. This causes StackOverflowError.

Iteration vs Recursion

Iteration Recursion
Uses loops like for, while, or do-while. Uses a method calling itself.
Usually uses less memory. Uses call stack memory for each method call.
Good for simple repeated tasks. Good for problems that can be divided into smaller similar problems.
No risk of stack overflow from method calls. Can cause stack overflow if base case is missing.
Easier to optimize for performance. Can be easier to understand for recursive problems.

When Should You Use Recursion?

  • When a problem can be divided into smaller similar subproblems.
  • When working with tree-like structures.
  • When solving problems like factorial, Fibonacci, searching, and backtracking.
  • When recursive logic makes the code easier to understand.

Complete Java Recursion Example

The following example demonstrates multiple recursive methods in one program.

JavaRecursionCompleteExample.java
Copy Try Download
public class JavaRecursionCompleteExample {

    static int factorial(int number) {
        if (number == 1) {
            return 1;
        }
        return number * factorial(number - 1);
    }

    static int sum(int number) {
        if (number == 0) {
            return 0;
        }
        return number + sum(number - 1);
    }

    static void countdown(int number) {
        if (number == 0) {
            System.out.println("Done");
            return;
        }
        System.out.println(number);
        countdown(number - 1);
    }

    public static void main(String[] args) {
        System.out.println("Factorial of 5: " + factorial(5));
        System.out.println("Sum up to 5: " + sum(5));
        countdown(3);
    }
}

Output:

Factorial of 5: 120
Sum up to 5: 15
3
2
1
Done

Code Explanation

  1. factorial() calculates the factorial of a number using recursion.
  2. sum() calculates the sum of natural numbers up to the given number.
  3. countdown() prints numbers in decreasing order and stops at 0.
  4. Each recursive method has a base case to stop recursion.
  5. The main() method calls all three recursive methods and prints the results.

Common Mistakes in Java Recursion

  • Forgetting to write a base case.
  • Writing a base case that is never reached.
  • Calling the recursive method with the same input again and again.
  • Using recursion when a loop would be simpler and more efficient.
  • Not understanding how values return from recursive calls.
  • Using recursive Fibonacci for very large inputs without optimization.

Recursion at a Glance

Concept Description
Recursion A method calling itself
Base Case Stopping condition
Recursive Case Method calls itself
Memory Used Call Stack
Risk StackOverflowError
Alternative Loops (Iteration)
Summary:
  • Recursion means a method calls itself.
  • A recursive method must have a base case.
  • The recursive case calls the same method with a smaller or simpler input.
  • Java uses the call stack to manage recursive calls.
  • Missing base case can cause StackOverflowError.
  • Recursion is useful for problems that can be broken into smaller similar problems.

Frequently Asked Questions

Recursion in Java is a technique where a method calls itself to solve a problem. The method continues calling itself until a stopping condition is reached.

A recursive method is a method that calls itself directly or indirectly to solve a smaller version of the same problem.

A base case is the stopping condition in a recursive method. It prevents the method from calling itself forever.

A recursive case is the part of a recursive method where the method calls itself with a smaller or simpler input.

A base case is important because without it, recursion may continue forever and cause a StackOverflowError.

StackOverflowError occurs when recursive method calls continue too many times and the call stack becomes full, usually because the base case is missing or never reached.

Java stores each recursive method call on the call stack. When the base case is reached, the method calls start returning one by one.

Yes, recursion can be used to calculate factorial by multiplying a number with the factorial of the previous number until the base case is reached.

Yes, recursion can be used to print Fibonacci series. However, recursive Fibonacci can be slow for large inputs because it repeats many calculations.

Iteration uses loops such as for or while, while recursion uses a method calling itself. Iteration usually uses less memory, while recursion uses call stack memory.

Recursion should be used when a problem can be divided into smaller similar subproblems, such as factorial, Fibonacci, tree traversal, searching, and backtracking.

No, recursion is not always better than loops. Loops are often more memory efficient, while recursion can make some problems easier to understand.

Yes, a recursive method can return a value. Examples include factorial, sum of natural numbers, and Fibonacci methods.

If the recursive call uses the same input repeatedly and never moves toward the base case, recursion may become infinite and cause StackOverflowError.

Common mistakes include forgetting the base case, writing a base case that is never reached, using the same input repeatedly, and using recursion when a loop would be simpler.

Next step: Learn Java Arrays

🚀 Continue to Java Arrays →

🧠 Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: Recursion | Language: Java

Q1. What is the recursive case in this factorial method?
static int factorial(int n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
Q2. Which construct is used in iteration?
Q3. What will be the output of this code?
public class Test {
    static void print(int n) {
        if (n > 3) {
            return;
        }
        System.out.print(n + " " );
        print(n + 1);
    }

    public static void main(String[] args) {
        print(1);
    }
}
Q4. What is recursion in Java?
Q5. Which memory structure keeps track of recursive method calls in Java?
Q6. Which statement is true about recursion?
Q7. What will fibonacci(5) return if fibonacci(0)=0 and fibonacci(1)=1?
Q8. What is the base case in this factorial method?
static int factorial(int n) {
    if (n == 1) {
        return 1;
    }
    return n * factorial(n - 1);
}
Q9. What will factorial(5) return?
Q10. Which is a common mistake in recursion?
Q11. In Fibonacci recursion, which values are usually base cases?
Q12. What should recursive calls do to eventually stop?
Q13. What is the purpose of a base case in recursion?
Q14. What can happen if recursion has no base case?
Q15. What is the recursive case?
Q16. What will be the output of this code?
public class Test {
    static int sum(int n) {
        if (n == 0) {
            return 0;
        }
        return n + sum(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(sum(5));
    }
}
Q17. Which statement is true about recursive Fibonacci for large inputs?
Q18. What is a recursive method?
Q19. What is the output of this recursive method call printReverse(3)?
static void printReverse(int n) {
    if (n == 0) {
        return;
    }
    System.out.print(n + " " );
    printReverse(n - 1);
}
Q20. Which one is usually more memory efficient for simple repeated tasks?

🎉 Great job! Continue learning Java step by step.