5

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.

Chen Xie
  • 3,849
  • 8
  • 27
  • 46

3 Answers3

13

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
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Here is an Operator Precedence for future reference [JavaOperatorPrecedenceTable](http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html). Good answer, very clear and concise – Rcordoval May 18 '18 at 05:17
5

The operator & has a lower precedence than +.

What you have actually written is:

n = ( n + 0 ) &1;

I added parentheses to clarify.

Since n is an even number, the outcome of that expression is zero.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
0

in first case,n will plus 0 first and then and 1

n = n+0&1 -> n = (n + 0)&1 -> 0
n+=0&1 ->n+=(0&1)->n
Kevin Su
  • 542
  • 2
  • 6
  • 24