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);
The bitwise OR assignment operator ( |= ) uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable.
In Java, bitwise operators perform operations on integer data at the individual bit-level. Here, the integer data includes byte , short , int , and long types of data. There are 7 operators to perform bit-level operations in Java.
Bitwise AND Assignment Operator means does AND on every bit of left operand and right operand and assigned value to left operand. x&=y. x=x&y. |= Bitwise inclusive OR Assignment Operator means does OR on every bit of left operand and right operand and assigned value to left operand.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With