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.
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:is equivalent to:
From JLS section 15.14.2:
Given that you don’t use
iagain afterwards (and thus any side-effect on it is pointless), why not just simplify your life?(As with all parameters in Java, you’re seeing pass-by-value – changing the value of
iin the method does not change the value of the caller’s argument.)