What does | mean in Java with examples

In this post, I will be sharing what does | operator mean in Java. According to Java docs, | (pronounced as a pipe) is a bitwise inclusive OR operator. It is a binary operator. If either of the operands is 1 then it returns 1, else 0.

Read Also: What does ! mean in Java with examples

  ðŸ’¡ Did You Know?

The bitwise OR operator(|) should not be confused with the logical OR(||) operator in Java.

Truth table of bitwise OR operator

bitwise inclusive OR operator in java

The above table represents the Truth table for the bitwise OR operator.

Syntax
 (operand1 | operand2) 

Example of | in Java

 15 = 00001111  (In Binary)
20 = 00010100  (In Binary)

Bitwise Inclusive OR operation of 15 and 20

   00001111
 | 00010100
 ----------------
   00011111 (= 31 in Decimal)

Java Program for | bitwise inclusive OR operator

 public class BitwiseInclusiveOR {
    public static void main(String args[]) {
      int num1 = 15;
      int num2 = 20;
      int result = num1 | num2;
      System.out.println("num1 | num2 = " + result);
    }
}


Output:
num1 | num2 = 31

What is the difference between | and || in Java

There are few differences between the bitwise OR operator (|) and the logical OR operator(||).

1. The first difference between them is that the logical OR operator works on boolean expressions and return boolean values(i.e true or false). On the other hand, the bitwise OR operator works on binary digits of integer values(byte, int, char, short and long) and returns an integer.

2. The logical OR operator always evaluates the first boolean expression and depending on its result it may or may not evaluate the second boolean expression. The bitwise OR operator always evaluates both the operands.

That's all for today. Please mention in the comments in case you have any questions related to what does | (pipe) mean in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry