2

In a project, I see the following code:

//f is a File
boolean acceptable = true;
acceptable &= sweepFilename != null;
acceptable &= f.getName().equals(sweepFilename.toString()); // parsable
acceptable &= id == null || id.equals(sweepFilename.getId());
acceptable &= length == null || length.equals(sweepFilename.getLength());
acceptable &= f.getName().toLowerCase().endsWith(SweepFilename.EXTENSION);
acceptable |= f.isDirectory();
return acceptable;

Can someone explain me what the &= and |= means?

I understand it as, if acceptable is true then also check the right side and assign the value of the operation (false/true) to acceptable, so that if it is false, then it will not need to check the right side.

2
  • 4
    x &= y; = x = x & y; Commented Aug 31, 2012 at 8:15
  • And & in turn is the bitwise AND operator. Commented Aug 31, 2012 at 8:18

5 Answers 5

9

Just like

a += b;

means

a = a+b;

, you have

a &= b;

meaning

a = a&b;

And of course the same for |=.

You have the same construct for other operators in most languages whose syntax inherits from the C language. Look for example at this : What does ">>=" mean in Linux kernel source code?

See also the complete list of assignment operators in java.

Sign up to request clarification or add additional context in comments.

Comments

3

+=, -=, *=, /=, &=, |= and other such operators are in most languages simply shorthands for a = a + b and equivalent.

Comments

1

'&' and '|' are bitwise operators. When used with '=' operator, these are just shortcuts for saying:

a&=b the same as a=a&b

Now, what does the a&b returns? It returns the logical 'AND', so it compares bits. As for boolean values (which are just named constants in Java), they represent 0 and 1 bit (for 'false' and 'true', respectively)

But you can use them with other integer types as well (short, int, long).

boolean a = true;
boolean b = false;
a &= b; // it acts like && and || for boolean values
System.out.println(a); //false

int i = 2;
int j = 3;        
System.out.println(Integer.toBinaryString(i));
System.out.println(Integer.toBinaryString(j));

System.out.println(i&=j); // prints binary '10' == 2 decimal
System.out.println(i|=j); // prints binary '11' == 3 decimal

Comments

0

As & is not a short cut operator, it might not be as efficient as using &&. If you did it might look like this.

return (sweepFilename != null 
        && f.getName().equals(sweepFilename.toString())
        && (id == null || id.equals(sweepFilename.getId()))
        && (length == null || length.equals(sweepFilename.getLength()))
        && (f.getName().toLowerCase().endsWith(SweepFilename.EXTENSION))) 
        ||  f.isDirectory();

Comments

0

The syntax x &= y is equivalent to x = x & y

and

The syntax x |= y is equivalent to x = x | y

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.