Software Development

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.

[wp_ad_camp_1]

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

[wp_ad_camp_2]

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.

[wp_ad_camp_3]

Our Existing Codes

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

[wp_ad_camp_4]

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.

[wp_ad_camp_5]

Outputs

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like