programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Could someone explain "|=" and "&=" assignment operations?

Greenhorn
Posts: 22
Could someone explain "|=" and "&=" assignment operations?

I'm not exactly sure what these operations do and where one would use them in practice.

Thanks!

Rancher
Posts: 3742
16
|= does a bitwise OR of the left and right hand operands
&= does a bitwise AND of the left and right hand operands

The result is assigned to the left hand operand.

Java Cowboy
Sheriff
Posts: 16079
88
Note that operators of the form "a X= b" are just a short-hand notation of "a = a X b".

So "a |= b" is the same as "a = a | b" and "a &= b" is the same as "a = a & b".

Marshal
Posts: 57437
175
All sorts of obscure ways you can use them in practice. About a year back we had discussion about how to implement the sort of LED lamps which have seven components in, to show numbers on screen. One way is to have different binary numbers which correspond to the different displays so "8" would come out as 01111111 (it is the only number where all seven bars are illuminated). To find out whether bar 0 is illuminated, you can "and" the number with 00000001.

A typical AND calculation follows:-
10101010 AND
00000001
________
00000000
This particular sum gives 0 throughout because there are no pairs of bits with 1 in both, whereas the following doesn't give 0:-
10101011 AND
00000001
________
00000001

Or gives 1 if either or both the bits at a particular location are 1. copying and pasting gives:-
10101010 OR
00000001
________
10101011

10101011 OR
00000001
________
10101011

There is also XOR (^) which gives 1 if the two bits at the same location are different.
10101010 XOR
00000001
________
10101011

10101011 XOR
00000001
________
10101010

As you have been told | means OR & means AND (and ^ means XOR). a &= b; is shorthand for a = a & b;

CR

Ranch Hand
Posts: 133
I would check out Bruce Eckel's Thinking in Java for a good look at operators.

It is a great book and available free online. (easily googled)

 my overalls have superpowers - they repel people who think fashion is important. Tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS