Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Operators : |= bitwise OR and assign example [duplicate]

Tags:

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); 
like image 923
Rachel Avatar asked Apr 13 '12 13:04

Rachel


People also ask

What does |= mean in Java?

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.

What is this >>> Bitwise operator in Java?

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.

What is bitwise assignment operator explain with example?

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.


1 Answers

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 ORs 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.

like image 84
Graham Borland Avatar answered Oct 21 '22 18:10

Graham Borland