Reputation: 1943
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.
Upvotes: 8
Views: 9593
Reputation: 1503140
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.)
Upvotes: 23
Reputation: 778
It behaves as expected it should, you probably want to replace i++
with ++i
.
Check the oracle documentation on how to use the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
(excerpt from the linked page)
Upvotes: 4
Reputation: 13925
i++
means that: "use value of i and then increment it". It will always be zero when passed down. It is a value type, not a reference type. If that would be an object, that would be no problem because it would be handled as reference.
Upvotes: 1
Reputation: 137412
The ++
operator works just as expected. it first returns the value of the variable, and then increases the variable, hence you always pass 0.
This:
doStuff(i++);
is like:
int x = i;
i += 1;
doStuff(x);
Upvotes: 2