Java : A pipe used in a print statement in java?

587 views Asked by At

What is it when a pipe is used in print statement in java? For example

System.out.println(6 | 3);

Output : 7

System.out.println(6 | 4);

Output : 6

3

There are 3 answers

0
SASIKUMAR SENTHILNATHAN On BEST ANSWER

Quite simple

System.out.println(6 | 3);

Performing "OR" operation of two values using corresponding binary values.

6 - 0 1 1 0
3 - 0 0 1 1 (OR)
-------------
    0 1 1 1 (7)
-------------

System.out.println(6 | 4);

6 - 0 1 1 0
3 - 0 1 0 0 (OR)
-------------
    0 1 1 0 (6)
-------------
0
Peter Pan On
          6 | 3  6 | 4
6 binary:  110    110
another:   101    100
bin or:    111    110
transform:  7      6  
0
Elliott Frisch On

It's a binary bitwise or operator, and it produces an int. We can inspect the values in binary and decimal with a small program like

int i = 6;
for (int j = 3; j < 5; j++) {
    System.out.printf("%d (%s) | %d (%s) = %d (%s)%n", i,
            Integer.toBinaryString(i), j, Integer.toBinaryString(j),
            (i | j), Integer.toBinaryString(i | j));
}

And the output is

6 (110) | 3 (11) = 7 (111)
6 (110) | 4 (100) = 6 (110)