Difference between | and || in Java

1. Introduction

In Java, the | and || operators are both used to evaluate boolean expressions, but they work differently. The | operator is the bitwise OR operator when used with numbers, and it is the non-short-circuit logical OR operator when used with boolean values. The || operator is the short-circuit logical OR operator.

2. Key Points

1. | evaluates both operands all the time when used as a logical OR operator.

2. || evaluates the right-hand operand only if the left-hand operand is false.

3. | is also a bitwise operator and operates on individual bits of integer types.

4. || provides performance benefits as it stops evaluating as soon as a true operand is found.

3. Differences

| (OR) || (Short-circuit OR)
Evaluates both operands regardless of the first one's value. Evaluates the second operand only if the first is false.
Can be used as both a bitwise and logical operator. Used only as a logical operator.
No performance optimization in Boolean expressions. Can provide performance optimization in boolean expressions.

4. Example


public class OrOperators {
    public static void main(String[] args) {
        int a = 2; // 010 in binary
        int b = 4; // 100 in binary

        // Step 1: Using the bitwise OR operator
        int result = a | b; // This will be 110 in binary or 6 in decimal
        System.out.println("Bitwise OR result: " + result);

        // Step 2: Using the logical OR operator
        boolean firstCondition = false;
        boolean secondCondition = true;

        // The | operator evaluates both conditions
        if (firstCondition | secondCondition) {
            System.out.println("Using | operator: at least one condition is true.");
        }

        // The || operator does not evaluate the second condition because the first is true
        if (firstCondition || secondCondition) {
            System.out.println("Using || operator: at least one condition is true.");
        }
    }
}

Output:

Bitwise OR result: 6
Using | operator: at least one condition is true.
Using || operator: at least one condition is true.

Explanation:

1. The bitwise OR operation between a and b results in 6, as it operates on each bit of the integers.

2. The logical OR | evaluates both firstCondition and secondCondition regardless of the value of the first one.

3. The short-circuit OR || evaluates firstCondition, finds it to be false, and then evaluates secondCondition. Since secondCondition is true, it stops and returns true.

5. When to use?

- Use | as a bitwise operator when working with bits or as a logical operator when you need to evaluate both conditions for their side effects.

- Use || when evaluating boolean expressions where the second condition does not need to be evaluated if the first one is true, which can be more efficient.

Comments