Reputation: 5609
Consider this simple code:
// E1
public void doTest(String pattern) {
int counter = 0;
while (counter < 3) {
counter = counter++;
}
System.out.println("Done");
}
This causes an infinite loop.
However if the statement that increments the counter is written like this:
E2. counter = ++counter;
or this
E3. counter++;
It terminates normally. I understand that the incrementing occurs after the assignment in the version that fails which explains why E2 works, but I thought java assigned the results of an increment in the variable that is incremented as in E3. So I'm perplexed as to why E1 fails but E3 does not.
Upvotes: 5
Views: 1378
Reputation: 41077
It is better to avoid this kind assignment.
The ++
is intended to be used by itself. If you want to increment by yourself you could have done counter += 1
.
Upvotes: 0
Reputation: 882
Replace
counter = counter++;
by: 1)
counter+=1;
or
2)
counter++;
Cheers!
Upvotes: 1
Reputation: 213193
counter = counter++;
The above code has no effect on counter
. It is effectively same as:
int temp = counter;
counter++;
counter = temp;
So, the value of counter
is not changing at all.
On the other hand, if you use:
counter = ++counter;
The counter is incremented first, and then is re-assigned to counter. Essentially, you can simply ignore the assignment part, and keep it simply this:
counter++; // Or ++counter
Upvotes: 17
Reputation: 25623
The problem is that the value of counter
at the end of the loop body is the same as it was at the beginning. The statement counter = counter++
is equivalent to:
int temp = counter;
counter = counter + 1;
counter = temp;
The postIncrement++
operator returns the value before the increment; the ++preIncrement
operator returns the incremented value.
Upvotes: 2