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
Anthony okoth
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
Eran
source
to share
Correct recursion could be:
public class LimitedRecursion {
public void m(int limit) {
if (limit == 0) {
System.out.println("finished2");
} else {
m(limit - 1);
}
}
}
+1
Ansu
source
to share
Something like this, add return statement
public static void main(String[] args) {
System.out.println(m(5));
}
public static String m(int limit) {
if (limit == 0) {
return "finished";
}
return m(limit - 1);
}
Output
finished
0
Ankur singhal
source
to share