-1

You may have already seen this somewhere, but I couldn't find a question on it. It's just a curiosity but I want to know what exactly is happening under the hood:

int j = 0;
for (int i = 0; i < 100; i++) {
   j = j++;
}

System.out.println(j);

The output of above will be 0, despite first appearances. Previously, I thought it would work as follows: j on the right (0) is assigned to j on the left (0), then j on the left is incremented to 1. My question is: since j on the left is at the same address as j on the right, why doesn't the increment stick afterwards? I had thought before that the post-incremental operator delayed execution until after the assignment. Like how this: "j = 0; k = j++;" will result in k == 0 and j == 1. So exactly what happens with the compiler when it's executing "j = j++;"?

JohnK
  • 6,865
  • 8
  • 49
  • 75
  • Have a look at this https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java (and then in your head evaluate `j++` to zero, increment `j` and then assign zero to `j` and there you go) – sfiss Mar 13 '20 at 16:06
  • 2
    Does this answer your question? [Java increment and assignment operator](https://stackoverflow.com/questions/24564603/java-increment-and-assignment-operator) – sfiss Mar 13 '20 at 16:11
  • Thanks sfiss, I didn't see that post. The third answer down in that post answers it; that the post-increment operator actually executes just *prior* to assignment, not after the entire statement has executed, as I had thought before. – AtomicPixel Mar 13 '20 at 17:01
  • To anyone reading this question, please do NOT down vote it. Thank you. – MasterJoe Mar 13 '20 at 20:37

1 Answers1

0

It's trivial:

since ++ is a suffix, it means the increment happens after the assignment.

So in this case you:

  1. assign j = j which leaves j at 0
  2. increment the right hand side j,

but this doesn't affect the new j since it happens after the assignment.

This would be similar to

int newj = oldj;
oldj = oldj+1;
ACV
  • 9,964
  • 5
  • 76
  • 81
  • That similarity is not exact; j's address never changes and if the value at that address is incremented after the assignment, then it would still go from 0-100; that was kind of my point in asking about what the compiler does exactly. But I see from a link in another question now that it actually submits the original value to the operator and executes the increment just PRIOR to assignment. Sorry if my wording caused any confusion. – AtomicPixel Mar 13 '20 at 16:55
  • To see what exactly happens, it is best to decompile to bytecode and check foryourself. That is a very interesting exercise to do – ACV Mar 13 '20 at 21:29