I cant for the life of me figure out why this returns 0 rather than 5. i keeps getting incremented before it hits the last return statement, however it always returns 0, from the first call in the stack. I would think that since the most recent call on the stack hits the return in the block i == 5 first it would return and print 5.
Returns 0
public static void main(String[] args) {
System.out.println(incrementI(0));
}
public static int incrementI(int i) {
if (i == 5){
return i;
} else {
incrementI(i + 1);
}
return i;
}
Returns 5
public static int incrementI(int i) {
if (i == 5){
return i;
} else {
return incrementI(i + 1);
}
}
I'm not looking for a code fix, but rather an explanation to why recursion works this way.