Assuming
boolean a = false;
I was wondering if doing:
a &= b;
is equivalent to
a = a && b; //logical AND, a is false hence b is not evaluated.
or on the other hand it means
a = a & b; //Bitwise AND. Both a and b are evaluated.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
From the Java Language Specification – 15.26.2 Compound Assignment Operators.
So
a &= b;is equivalent toa = a & b;.(In some usages, the type-casting makes a difference to the result, but in this one
bhas to bebooleanand 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;anda = a && b;. (Ifbis a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference whenbis a subexpression that has side-effects. In the&case, the side-effect always occurs. In the&&case it occurs depending on the value ofa.)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 ofa, and the potential saving of avoiding an unnecessary assignment toa. The analysis is not straight-forward, but unless the cost of calculatingbis non-trivial, the performance difference between the two versions is too small to be worth considering.