I have some problem understanding the compound assignment operator and the assignment operator in java. Can someone explain to me how these two operators really works? (Somwhere I found a really good example code using temporary variables to explain the working but sadly I've lost it.) Thank you very much in advantage. Here is my little example code for them (I already know the difference between prefix and postfix operators):
int k = 12;
k += k++;
System.out.println(k); // 24 -- why not (12+12)++ == 25?
k = 12;
k += ++k;
System.out.println(k); // 25 -- why not (1+12)+(1+12) == 26?
k = 12;
k = k + k++;
System.out.println(k); // 24 -- why not 25? (12+12)++?
k = 12;
k = k++ + k;
System.out.println(k); // 25 -- why not 24 like the previous one?
k = 12;
k = k + ++k;
System.out.println(k); // 25 -- OK 12+(1+12)
k = 12;
k = ++k + k;
System.out.println(k); // 26 -- why?
Note that in all cases, the assignment to k overwrites any incrementation that may happen on the righthand side.
Putting comments in-line:
int k = 12;
k += k++;
System.out.println(k); // 24
k++ means increment after you've used the value, so this is the same as coding k = 12 + 12
k = 12;
k += ++k;
System.out.println(k); // 25
++k means increment before you use the value, so this is the same as coding k = 12 + 13
k = 12;
k = k + k++;
System.out.println(k); // 24
k++ means increment after you've used the value, so this is the same as coding k = 12 + 12
k = 12;
k = k++ + k;
System.out.println(k); // 25
k++ means increment after you've used the value, so this is the same as coding k = 12 + 13
k = 12;
k = k + ++k;
System.out.println(k); // 25
++k means increment before you use the value, so this is the same as coding k = 12 + 13
k = 12;
k = ++k + k;
System.out.println(k); // 26
++k means increment before you use the value, which is then used again, so this is the same as coding k = 13 + 13
Here is a detailed explanation for the first case:
int k = 12;
k += k++;
System.out.println(k);
k += k++; is equivalent to:
k = k + (k++);
k + (k++); is evaluated from left to right.
The first k has a value of 12.
k++ is evaluated to the original value of k (i.e. 12); k is later incremented.
The other posts do a good job explaining the other cases.
But here is an interesting case that shows the evaluation from left to right and the post incrementation on the right:
int k = 12;
k = k + k++ + k;
System.out.println(k);
k + (k++) + k; is evaluated from left to right.
The first k has a value of 12.
Second k: k++ is evaluated to the original value of k (i.e. 12); k is later incremented.
Third k: now k has an incremented value of 13 (since it comes after the second k).
The total result is 37 (i.e. 12 + 12 + 13).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With