[java] Does the Java &= operator apply & or &&?

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.

This question is related to java operators

The answer is


Here's a simple way to test it:

public class OperatorTest {     
    public static void main(String[] args) {
        boolean a = false;
        a &= b();
    }

    private static boolean b() {
        System.out.println("b() was called");
        return true;
    }
}

The output is b() was called, therefore the right-hand operand is evaluated.

So, as already mentioned by others, a &= b is the same as a = a & b.


i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

It's the last one:

a = a & b;

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.