Java doesn't have a predefined recursion depth limit. As a result the recursion below (a dummy method that returns the value) throws java.lang.StackOverflowError
after 62844 (with static) and 14002 (without static) iterations.
public static int testRecursion(int number) {
if (number == 1) {
return 1;
} else {
int result = 1 + testRecursion(number - 1);
return result;
}
}
public int testIteration(int number){
int result = 0;
while (number > 0){
result++;
number--;
}
return result;
}
I have two concerns:
- Iteration method works correctly for all positive int values, whereas recursion throws an exception
- Changes to a method change the recursion depth at which the exception will be thrown.
Recursion in Java seems like a way to add floating bugs. Recursion depth is greater than a magic number? Program throws exception. Author modified recursive method - allowed recursion depth decreased and an exception is thrown again.
Recursions are widely used in Java. Does it mean that recursion limit is rarely reached in practical situations? Or are there some general and robust methods to deal with floating recursion depth limit?
I've read these questions:
- How to convert this recursive problem to iterative? Line Simplification algorithm fails to run due to Maximum Recursion Depth being hit
- Recursion or while loops
- What are the advantages of recursion compared to iteration?
But none of those questions discuss a problem of recursion depth in Java.
-Xss
). The fact that most people aren't even aware of this fact should tell you how often this limit is hit. As a side note - doing this, you're essentially trading heap space and some pre-written logic for stack space. As always, you should be mindful of the consequences of your choice and decide if this is the best thing for you.static
keyword) drastically changes maximum recursion depth. This made me wonder: "sure, recursion can be more readable, but does it justify the Damocles sword of stack overflow?"