Java – Fixing Post-Increment (++) Behavior When Passed as a Parameter

javapost-incrementpre-increment

I came across the following issue:

private void doStuff(int i) {
   if(i>10) {
      return;
   }
   doStuff(i++); 
}

public void publicMethod() {
   doStuff(i);
}

I would expect this to run doStuff 10 times and then return.

However i++ does not get executed before the doStuff is called again with 0.

Result is an infinite loop. I know how to fix it but I am wondering if this behaviour is correct or a bug.

Best Answer

Now I would expect this to run doStuff 10 times and then return, however i++ does not get execute before the doStuff is called again with 0.

Yes, the result of the post-increment operator is the original value... and then inside the next call to the method you've a new i. So in other words, this call:

doStuff(i++); 

is equivalent to:

int original = i;
i = original + 1;
doStuff(original);

From JLS section 15.14.2:

The value of the postfix increment expression is the value of the variable before the new value is stored.

Given that you don't use i again afterwards (and thus any side-effect on it is pointless), why not just simplify your life?

doStuff(i + 1);

(As with all parameters in Java, you're seeing pass-by-value - changing the value of i in the method does not change the value of the caller's argument.)

Related Question