Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

&= and |= in Java

Tags:

java

operators

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.

like image 821
Shervin Asgari Avatar asked Dec 20 '25 11:12

Shervin Asgari


2 Answers

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.

like image 177
Denys Séguret Avatar answered Dec 23 '25 00:12

Denys Séguret


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

like image 22
user1338062 Avatar answered Dec 23 '25 00:12

user1338062