dann.dev
dann.dev

Reputation: 2494

What is the &= operator for in Java

The Java tutorials here mention that &= is an assignment operator but doesn't seem to mention what it does.

What does &= do?

Upvotes: 6

Views: 314

Answers (2)

These are logical operator "AND" and assignment operator.

Boolean example:

Boolean a = true;
Boolean x = false;
a &= x;

Then:

a == false;

Logically it looks like

a = a & x

or

if( a & x )
{
  a = true;
}
else
{
  a = false;
}
  

Upvotes: 0

Niklas B.
Niklas B.

Reputation: 95348

a &= x

is equivalent to

a = (type of a)(a & x)

which in turn is a

  • bitwise AND of a and x in the case where a and x are integers or a
  • non short-circuiting logical AND in the case of a and x being booleans (which means that x will be evaluated in any case here, even if a is false).

There are several other binary operators which can be used with similar semantics, like +=, -=, *=, /=, %=, |=, <<=, ...

Upvotes: 16

Related Questions