Note the following points about the postfix change (increment/decrement) operator:
- A postfix operator assigns the value to the left operand and then change its value.
- If the variable of the left operand is different from that of the right operand, the variable of the left operand will have the original value of the variable with the postfix (i.e. the variable of the right operand) and the variable of the right operand will have the changed value.
- If the variable of the left operand is the same as that of the right operand, the variable will continue to have the original value i.e. the change won't have any effect. Although technically allowed, it's confusing and can cause bugs in your program/application.
In your case, you have done what is mentioned in point#3. After this assignment, i
will continue to have the value, 1
.
int i = 1;
i = i++;
Apart from this, since you have put these two lines under a loop, every time the loop will iterate, the variable, i
will be freshly created. In other words, old i
dies and a new i
is born with the initial value of 1
.
However, even if you declare i
outside the loop but assign the value, 1
to it (i.e. i = 1), its value will be reset in eadh iteration of the loop. If you intend to preserve the value of i
, you need to declare and initialize it outside the for
loop e.g. as follows:
int i = 1;
for (technique j : activeuser.techniques) {
i++;
System.out.print(i + j.tname + " and ");
}
Note that since you are not assigning the value of i
to any variable, using ++i
or i = i + 1
will have the same effect in the code given above.