Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The |= operator is a compound assignment operator that performs an inclusive OR operation between the left and right operands, subsequently assigning the computed result to the left operand. Depending on the data types of the operands, it functions as either a bitwise OR (for integral types) or a strict logical OR (for boolean types).

Syntax and Equivalence

leftOperand |= rightOperand;
Internally, the Java compiler evaluates A |= B as:
A = (TypeA) (A | B);
The left-hand operand is evaluated exactly once.

Behavior by Operand Type

1. Integral Types (byte, short, int, long, char)

When applied to integer types, |= performs a bitwise inclusive OR operation. The JVM compares the binary representations of both operands bit by bit. If either corresponding bit is 1, the resulting bit is 1. If both bits are 0, the resulting bit is 0.
int a = 5;      // Binary: 0101
a |= 3;         // Binary: 0011
// Result in a: 7 (Binary: 0111)

2. Boolean Type

When applied to boolean variables, |= performs a logical inclusive OR operation. If either the left or right operand is true, the left operand is assigned true. Unlike the short-circuit logical OR operator (||), the underlying | operator strictly evaluates both operands before performing the assignment.
boolean flag = false;
flag |= true; 
// Result in flag: true

Implicit Type Casting

A critical mechanical feature of the |= operator (and all compound assignment operators in Java) is that it automatically performs an implicit narrowing primitive conversion if the result of the OR operation is wider than the left operand’s type. When performing bitwise operations on types smaller than int (like byte or short), Java automatically promotes the operands to int before the operation. The |= operator handles the mandatory downcast back to the original type automatically.
byte b = 10;
// b = b | 5; // Compilation error: incompatible types (int cannot be converted to byte)
b |= 5;       // Compiles successfully. Equivalent to: b = (byte) (b | 5);
Master Java with Deep Grasping Methodology!Learn More