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 exceptionChanges 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 hitRecursion or while loopsWhat are the advantages of recursion compared to iteration?But none of those questions discuss a problem of recursion depth in Java.
Are recursions intrinsically less safe than iterations?
java;recursion
Recursion limit hits are indicated by corresponding messages and a recursion can easily be rewritten as iterations. This makes detection and fix easy.Recursions are typically used in situations where the recursion depth is low. As Ordous pointed out -Xss parameter can be tuned to address borderline cases. Deep recursive calls should be avoided. Tight loops are not really suited for recursive calls.