Java Language Recursion

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Recursion occurs when a method calls itself. Such a method is called recursive. A recursive method may be more concise than an equivalent non-recursive approach. However, for deep recursion, sometimes an iterative solution can consume less of a thread's finite stack space.

This topic includes examples of recursion in Java.

Remarks

Designing a Recursive Method

When designing a recursive method keep in mind that you need:

  • Base Case. This will define when your recursion will stop and output the result. The base case in the factorial example is:

    if (n <= 1) {
        return 1;
    }
    
  • Recursive Call. In this statement you re-call the method with a changed parameter. The recursive call in the factorial example above is:

    else {
        return n * factorial(n - 1);
    }
    

Output

In this example you compute the n-th factorial number. The first factorials are:

0! = 1

1! = 1

2! = 1 x 2 = 2

3! = 1 x 2 x 3 = 6

4! = 1 x 2 x 3 x 4 = 24

...


Java and Tail-call elimination

Current Java compilers (up to and including Java 9) do not perform tail-call elimination. This can impact the performance of recursive algorithms, and if the recursion is deep enough, it can lead to StackOverflowError crashes; see Deep recursion is problematic in Java



Got any Java Language Question?