-7

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);
    }               
}
6
  • 1
    java !== javascript Commented Oct 10, 2016 at 0:05
  • 4
    What's something() ?? Is that supposed to be incrementI()? Commented Oct 10, 2016 at 0:06
  • What does something(int i) do? Commented Oct 10, 2016 at 0:09
  • Where is the recursion? Commented Oct 10, 2016 at 0:18
  • Yes, something is suppose to be inrementI(), quick typo, Thanks! Commented Oct 10, 2016 at 0:44

1 Answer 1

3

Imagine you wrote such function:

public static int square(int x) {
    pow(x, 2);
    return x;
}

It will compute the square of x. But then computed square will not affect anything and the function will return just x.

Now look carefully at your code

if (i == 5){
    return i;           
} else {
    something(i + 1);
}
return i;

If i is not 5, something(i + 1) will be called. Then it will return some value but this value will not affect to anything. And then incrementI function will return just i, in your case it's 0.

Sign up to request clarification or add additional context in comments.

2 Comments

something is suppose to be inrementI(), quick typo!
@NightSkyCode, Looks like you're missing Pavel's point. The incrementI(i) function in your first example always returns i: It immediately returns 5 if i==5, otherwise it does some stuff, and then it returns i. It doesn't matter what "some stuff" is. It doesn't matter whether "some stuff" is a function call named something() or whether it is a recursive call to incrementI(). Either way, it does whatever, and then it ignores the result of doing whatever, and then it returns i.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.