Recursion in Java


Recursion is a programming practice that allows a method to call itself as often as necessary. The method that calls itself is called as recursive method. We can find its application while calculating factorial and Fibonacci series. Recursion reduces a multi-line complex code to significantly lesser lines which makes the code more simpler and easy to understand.

In this article, we will learn recursion and apply its concept to solve a few problems. Also, we will discuss the most common error found while working with the recursion in Java.

Recursion

Every interface, class, object, variable and method of a running program is stored in distinct reasons of computer memory. The reference variables, names of methods and classes are stored in the stack and their values are stored in the heap. Similarly, the recursive methods get spaces in stack memory for each method call and stay till the method execution stops. After execution finishes, they get removed from stack and the flow of program is restored to the main() method where the method call started.

While working with recursion make sure to provide a base case that forces the recursive method to return the result or terminate the method calling.

Example

In the following example, we will demonstrate the use of recursion with a simple multiplication operation. First, we create a parameterized method that accepts an integer type parameter. In this method, we define a base case using if-else block. This method will call itself 5 times in the else block, until the if block gets true.

public class Overflw {
   public static void methodA(int n1) {
     if(n1 == 5) {
       // base condition to terminate the recursive method
       int n2 = 5;
       int mult = n1 * n2;
       System.out.println("Value of n1 and n2 multiplication is: " + mult);
     } else {
       methodA(n1 + 1); 
       // calling the method 
     }
   }
   public static void main(String []args) {
     int n1 = 0;
     methodA(n1);  
     // first method call
   }
} 

Output

Value of n1 and n2 multiplication is: 25

StackOverflowError in Java

Whenever a recursion process starts it automatically gets defined with a fixed stack size. During each method call, a call frame gets created on the call stack and it continues until method invocation ends. When there is no space left for a new stack frame in the stack space of computer memory then we encounter StackOverflowError.

Syntax

import java.lang.StackOverflowError;

This class is available in ‘java.lang’ package. We don’t necessarily need to import this package. Usually, the classes of this package are automatically available without importing them into our program. However, there are some exceptions too.

Example

The following example illustrates the StackOverflowError.

import java.lang.StackOverflowError;
public class Overflw {
   public static void methodA(int n1) {
     n1++;
     methodB(n1);
   }
   public static void methodB(int n1) {
     n1++;
     methodA(n1);
   }
   public static void main(String []args) {
     int n1 = 0;
     methodA(n1);
   }
}

Output

Exception in thread "main" java.lang.StackOverflowError
	at Overflw.methodB(Overflw.java:9)
	at Overflw.methodA(Overflw.java:5)
	at Overflw.methodB(Overflw.java:9)
	at Overflw.methodA(Overflw.java:5)
	at Overflw.methodB(Overflw.java:9)
	at Overflw.methodA(Overflw.java:5)
	at Overflw.methodB(Overflw.java:9)
   at Overflw.methodA(Overflw.java:5)
	at Overflw.methodB(Overflw.java:9)
	at Overflw.methodA(Overflw.java:5)
	at Overflw.methodB(Overflw.java:9)
	at Overflw.methodA(Overflw.java:5)
	at Overflw.methodB(Overflw.java:9)

As you can see the above output, we are getting StackOverflowError. What we have done in the code is that we have created two parameterized user-defined methods named ‘methodA’ and ‘methodB’. In the main method, we have declared and initialized an integer variable ‘n1’ to 0 and called the ‘methodA’ along with an argument ‘n1’. Now, the ‘methodA’ called the ‘methodB’ with the increment value of ‘n1’. Again, the ‘methodB’ called the ‘methodA’ and this process repeats itself many times. Hence at some point, the stack size created for this program gets exhausted resulting in the following error.

The following measures we can take to handle StackOverflowError −

  • Carefully inspect those lines that repeat themselves and try to find the reason why they didn’t terminate.

  • The default stack size may be either 512KB Or 1MB depending on the installed Java Virtual Machine but we can increase the size of stack manually to avoid this error. However, this technique is rarely used.

Conclusion

The recursive approach is a bit slower than the iterative approaches like for loop and while loop. If the base case failed to handle the recursion then it will result in stack overrun or more specifically StackOverflowError. In this article, we have learned recursion and also StackOverflowError.

Updated on: 16-May-2023

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements