Java termination recursion
I am involved in recursive method invocation in java. I keep getting StackOverFlowError
from my implementation:
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
}
}
i set the limit to 42 basically. Can anyone point me in the right direction? It was supposed to end oncelimit == 0
+3
source to share
3 answers
This does not terminate the recursion, since you do not exit the method when the condition is met, and you still make the following recursive call ( m(limit - 1);
):
if (limit == 0) {
System.out.println("finished2");
}
m(limit - 1);
This will end the recursion:
if (limit == 0) {
System.out.println("finished2");
return;
}
m(limit - 1);
+8
source to share