Java Language Operators The Bitwise and Logical Operators (~, &, |, ^)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The Java language provides 4 operators that perform bitwise or logical operations on integer or boolean operands.

  • The complement (~) operator is a unary operator that performs a bitwise or logical inversion of the bits of one operand; see JLS 15.15.5..
  • The AND (&) operator is a binary operator that performs a bitwise or logical "and" of two operands; see JLS 15.22.2..
  • The OR (|) operator is a binary operator that performs a bitwise or logical "inclusive or" of two operands; see JLS 15.22.2..
  • The XOR (^) operator is a binary operator that performs a bitwise or logical "exclusive or" of two operands; see JLS 15.22.2..

The logical operations performed by these operators when the operands are booleans can be summarized as follows:

AB~AA & BA | BA ^ B
001000
011011
100011
110110

Note that for integer operands, the above table describes what happens for individual bits. The operators actually operate on all 32 or 64 bits of the operand or operands in parallel.

Operand types and result types.

The usual arithmetic conversions apply when the operands are integers. Common use-cases for the bitwise operators


The ~ operator is used to reverse a boolean value, or change all the bits in an integer operand.

The & operator is used for "masking out" some of the bits in an integer operand. For example:

int word = 0b00101010;
int mask = 0b00000011;   // Mask for masking out all but the bottom 
                         // two bits of a word
int lowBits = word & mask;            // -> 0b00000010
int highBits = word & ~mask;          // -> 0b00101000

The | operator is used to combine the truth values of two operands. For example:

int word2 = 0b01011111; 
// Combine the bottom 2 bits of word1 with the top 30 bits of word2
int combined = (word & mask) | (word2 & ~mask);   // -> 0b01011110

The ^ operator is used for toggling or "flipping" bits:

int word3 = 0b00101010;
int word4 = word3 ^ mask;             // -> 0b00101001

For more examples of the use of the bitwise operators, see Bit Manipulation



Got any Java Language Question?