I also stumbled by the trickiness of post-increment operator while preparing for a Java certification exam. Most, even the experienced, think post-increment (++) operator increments the variable after the execution of the statement, just as @bartektartanus stated above. This thinking is good enough for most real world coding, but breaks down if a post/pre-incremented/decremented variable occurs more than once within a statement. Looks like the so-called interview/knowledge test questions promptly check for this loose assumption. It is worth breaking this up. The accepted answer above is not so helpful for a concise, logical mnemonic.
public class Test {
static int x = 10;
public static void main(String[] args) {
print(x++);
}
private static void print(int x) {
System.out.println(x);
System.out.println(Test.x);
}
}
Output
10
11
Per the common assumption, the static variable x would be incremented after completion of the call to the print
method. But when checked inside the method, it has already been incremented. So, post- increment, decrement operaters submit the variable value to the method or operator to which they are parameters, and increment/decrement the associated variable immediately before the operator/method gets executed. The pre-increment/decrement operation is somewhat less confusing, but again even this happens per method or operator, not the whole statement.
// The OP
int x = 10;
x = x++; // x = 10. x does get incremented but before the assignment operation
int x = 10;
x = x++ + x; // x = 21. x got incremented immediately after the addition operator grabbed its value.