NightSkyCode - 6 months ago 23

Java Question

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;

}

`public static int incrementI(int i) {`

if (i == 5){

return i;

} else {

return incrementI(i + 1);

}

}

Answer

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`

.