Pipe (|) operator in Java

bentham picture bentham · Jul 22, 2010 · Viewed 60.1k times · Source

I've got this statement in Java:

System.out.println(3|4); 

Why is the output 7?

Answer

Jonathon Faust picture Jonathon Faust · Jul 22, 2010

It's a bitwise OR operation. It's modifying things at a binary level.

             011                     3
in binary: | 100     in decimal:  |  4
             ___                   ___
             111                     7

Open Windows calc using scientific mode. You can flip between decimal and binary (and hex) and perform bitwise operations including or, and, xor, etc.

To do a bitwise or in your head or on paper, compare each digit of the same ordinal. If either number is a 1, the result at that ordinal will be 1.