Java compound assignment operator and assignment operator

I encountered some problems in understanding compound assignment operators and assignment operators in Java Can someone explain to me how these two operators work? (somwhere I found a very good example code that uses temporary variables to explain work, but unfortunately I've lost it.) Thank you very much for your advantages This is my small example code (I already know the difference between prefix and suffix 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?

Solution

Note that in all cases, the assignment of K overrides any increment that may occur on the right

Put comments on one line:

int k = 12;
   k += k++;   
   System.out.println(k);  // 24

K means to increment after using this value, so this is the same as coding k = 12

k = 12;
   k += ++k; 
   System.out.println(k); // 25

K means to increment before using this value, so this is the same as coding k = 12 13

k = 12;
   k = k + k++; 
   System.out.println(k); // 24

K means to increment after using this value, so this is the same as coding k = 12

k = 12;
   k = k++ + k; 
   System.out.println(k); // 25

K means to increment after using this value, so this is the same as coding k = 12 13

k = 12;
   k = k + ++k; 
   System.out.println(k); // 25

K means to increment before using this value, so this is the same as coding k = 12 13

k = 12;
   k = ++k + k; 
   System.out.println(k); // 26

K means to increment before using the value and then use the value again, so this is the same as coding k = 13

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>