Java – Limit Recursive method calls

This post demonstrates how to limit the number of recursive calls to avoid StackOverflowError in Java.

Recursive method call

Recursive method call is invoking the method from within the same method. For example, these codes have a helloWorld() method that displays the text "Hello World" and calls the same method on line 4.

If these codes are run, we get around ~2344 lines of text as shown below.

Recursion is a very powerful concept that can simplify a solution to a problem. “Simplify” means the solution uses less codes, elegant, and concise.

Real-life Simple Example

Sample Data

On the left side, we have the levels of method calls.

  • Level 1 has A
  • Level 2 has A and B
  • Level 3 has D, E, C1, and C2
  • Level 4 has D1, D2, E1, and E2

For our purpose, we want to prevent the codes from going to level 3 and beyond.

Our Existing Codes

Our simple example consists of 2 files – TwoSiblingsBean.java and TwoSiblingsDemo.java.

This outputs the following.

These codes went to level 3 and beyond.

Limit Recursive Calls

We could change the TwoSiblingsDemo class to limit the number of recursive calls. Here are the new codes.

Outputs

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert