Operator "| "In Java

17

I can not find any material on the internet explaining the utility of the "|" operator in Java.

I know there is the "||" (or) used to test conditions.

if(foo == 'a' || foo == 'b') 

But what about the "|" operator? How useful is it?

My question came up after finding the following code snippet:

int foo = START|MIDDLE|END;
    
asked by anonymous 29.09.2014 / 20:46

2 answers

17

The operator || is the "or" operator for logical operations ("boolean" or "bulianas"):

if(foo == 'a' || foo == 'b') 

It is the same as saying foo = a or foo = b , that is, any of the results being true, the condition is satisfied.

Now the | operator is the "binary OU", it merges the bits of the parameters like this:

0 | 0 = 0 
0 | 1 = 1 
1 | 0 = 1 
1 | 1 = 1 

The logic is the same as || (either side being true, it results in true), but it applies to the individual bits of each of the parameters. As an example, 3 | 5 results in 7 , since 3 is 0011 in binary, and 5 is 0101 :

  0011
| 0101
= 0111

Note that in this case, the operation performed leaves a numeric result, since we are working with the values, not with a mere "true" or false "generalized", as in the case of || .


Normally the flags of a program are usually defined as constants like this:

#define FLAG1 0x0001 // equivale a 0001 em binário
#define FLAG2 0x0002 // equivale a 0010 em binário
#define FLAG3 0x0004 // equivale a 0100 em binário
#define FLAG3 0x0008 // equivale a 1000 em binário

Just when you make a ( FLAG1 | FLAG3 ) have an unambiguous result:

FLAG1 | FLAG3 results in 5 in the given example, no other combination gives this.

    
29.09.2014 / 20:51
6

The | operator is the "bitwise OR". It performs the bit-by-bit OR operation and as its name indicates it is used to perform operations on the bits that make up integer variables.

    
29.09.2014 / 20:51