3) Java Methods Lesson

What is Recursion?

5 min to complete · By Ryan Desmond

Recursion is what happens when a method calls itself (maybe you could call it method-ception ;) ), and this process can be used for a range of problems.

How to do Recursion in Java?

To start with recursion, the only step required is to create a method and then call that same method in its method body. That said, you must also build in an "escape clause" or an "exit strategy" to get out of any recursive method. Otherwise, you'll essentially have an infinite loop leading to a StackOverflowException - no good.

public static void recursiveMethod(int num){
   // this method calls itself recursively
   System.out.println(num)
   recursiveMethod(num - 1);
   // this will currently result in an infinite loop
   // that will lead to a StackOverflowException
}

The example below has an escape clause that will stop this recursive method from calling itself forever.

public static void recursiveMethod(int num){
   // this is the escape clause
   if (num < 0){
      return;
   }
   System.out.println(num)
   recursiveMethod(num - 1);
}

Why Use Recursion?

A recursive method can iteratively reduce a task into subtasks until the larger task is complete. A popular recursive problem is computing the factorial number of a given number N. 

Recursion is a great way to solve some problems, but it must be known that recursion can cause quite a headache. An incorrect recursive call could result in a StackOverFlowError, which is when the stack of method calls to be made is too large. Most problems have an iterative solution as well, so it is often best to complete both and decide which is more efficient or user-friendly.

Java Recursion Example

Below is an example of recursion in action using the factorial problem mentioned above.

public class RecursiveFactorial {
    public static void main(String[] args) {
        int x = factorial(10);
        System.out.println(x);
    }

    static int factorial(int x){
        int total;        
        if(x == 1)
            return 1;    
        // otherwise, factorial is called and passed x - 1, 
        // reducing x each time until it reaches 1. 
        total = factorial(x - 1) * x;
        return total;
    }
}

The recursive method multiplies x by the result of factorial(x - 1) until x reaches 1. When x reaches 1, the method returns each result off the stack and starts completing the calculations one by one.

Here is a great video that visualizes a recursive method. Specifically around the 2:20 mark.

Summary: What is Java Recursion?

  • Recursion is when a method calls itself
  • A recursive method can iteratively reduce a task into subtasks until the larger task is complete
  • Recursion can become a headache and is not always the best solution due to heavy use of the Stack
  • An incorrectly managed recursive method will often result in a StackOverFlowError