Does the Java &= operator apply & or &&?
Solution 1:
From the Java Language Specification - 15.26.2 Compound Assignment Operators.
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
So a &= b;
is equivalent to a = a & b;
.
(In some usages, the type-casting makes a difference to the result, but in this one b
has to be boolean
and the type-cast does nothing.)
And, for the record, a &&= b;
is not valid Java. There is no &&=
operator.
In practice, there is little semantic difference between a = a & b;
and a = a && b;
. (If b
is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference when b
is a subexpression that has side-effects. In the &
case, the side-effect always occurs. In the &&
case it occurs depending on the value of a
.)
On the performance side, the trade-off is between the cost of evaluating b
, and the cost of a test and branch of the value of a
, and the potential saving of avoiding an unnecessary assignment to a
. The analysis is not straight-forward, but unless the cost of calculating b
is non-trivial, the performance difference between the two versions is too small to be worth considering.
Solution 2:
see 15.22.2 of the JLS. For boolean operands, the &
operator is boolean, not bitwise. The only difference between &&
and &
for boolean operands is that for &&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).
So in your case, if b
is a primitive, a = a && b
, a = a & b
, and a &= b
all do the same thing.