Java Operators : |= bitwise OR and assign example

bit-manipulation, java, operators, variable-assignment

Solution

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 `matches` is a `boolean`; this means that the bitwise operators behave the same as logical operators.

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

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

Problem

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); ```

Original source

Related problems