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:
k++means increment after you’ve used the value, so this is the same as codingk = 12 + 12++kmeans increment before you use the value, so this is the same as codingk = 12 + 13k++means increment after you’ve used the value, so this is the same as codingk = 12 + 12k++means increment after you’ve used the value, so this is the same as codingk = 12 + 13++kmeans increment before you use the value, so this is the same as codingk = 12 + 13++kmeans increment before you use the value, which is then used again, so this is the same as codingk = 13 + 13