Java “x += y” and “x = x+y” yields different result

  • A+

I came up with two expressions to assign value from a bit operation to a variable, and noticed "x+=y" and "x=x+y" yielded different results in this case:

public void random ()  {         int n =     43261596;         System.out.println(Integer.toBinaryString(n));         n = n + 0&1; //binary representation of n is 0         //n += 0&1;  //result is the same as n         System.out.println(Integer.toBinaryString(n)); } 

I did some research, and found the only case "x+=y" and "x=x+y" is not equivalent is when operant types are not the same, however in this case, "n" is type of int, and "0&1" shoud be a type of int (according to this question Why does bitwise AND of two short values result in an int value in Java?:

Because the Java Language Specification says that the result of non-long integer arithmetic is always an int.)

So I'm wondering why it yields different results.

The difference is operator precedence. + has precedence to &, but & has precedence to +=. So your operations translate to this:

n = (n + 0) & 1; // = n & 1 = 0 (when n is even) n += (0 & 1);    // = n + 0 = n 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: