Java Operators : |= bitwise OR and assign example

I just going through code someone has written and I saw usage, looking up on Java operators, it suggests bitwise or and assign operation, can anyone explain and give me an example of it?|=

Here is the code that read it:

    for (String search : textSearch.getValue())
         matches |= field.contains(search);

答案 1
a |= b;

is the same as

a = (a | b);

It calculates the bitwise OR of the two operands, and assigns the result to the left operand.

To explain your example code:

for (String search : textSearch.getValue())
    matches |= field.contains(search);

I presume is a ; this means that the bitwise operators behave the same as logical operators.matchesboolean

On each iteration of the loop, it s the current value of with whatever is returned from . This has the effect of setting it to if it was already true, or if returns true.ORmatchesfield.contains()truefield.contains()

So, it calculates if any of the calls to , throughout the entire loop, has returned .field.contains()true


答案 2

a |= b is the same as a = (a | b)

Boolean Variables

In a context, it means:boolean

if (b) {
    a = true;
}

that is, if is true then will be true, otherwise will be unmodified.baa

Bitwise Operations

In a bit wise context it means that every binary bit that's set in will become set in . Bits that are clear in will be unmodified in .baba

So if bit 0 is set in , it'll also become set in , per the example below:ba

  • This will set the bottom bit of an integer:

    a |= 0x01

  • This will clear the bottom bit:

    a &= ~0x01

  • This will toggle the bottom bit:

    a ^= 0x01;