Skip to main content

Operators

Bitwise Operators

In Java, bitwise operators are used to perform operations at the binary level on integer operands. There are six bitwise operators:

  1. Bitwise AND (&)
  2. Bitwise OR (|)
  3. Bitwise XOR (^)
  4. Bitwise complement (~)
  5. Bitwise Left shift (<<)
  6. Bitwise Right shift (>>).

Bitwise AND (&)

Performs a bitwise AND operation between corresponding bits of two operands.

If both bits are 1, the result bit is set to 1. Otherwise, it's set to 0.

int a = 5;   // binary: 0000 0101
int b = 3;   // binary: 0000 0011
int result = a & b;   // binary result: 0000 0001 (1 in decimal)

Bitwise OR (|)

Performs a bitwise OR operation between corresponding bits of two operands.

If at least one of the bits is 1, the result bit is set to 1. Otherwise, it's set to 0.

int a = 5;   // binary: 0000 0101
int b = 3;   // binary: 0000 0011
int result = a | b;   // binary result: 0000 0111 (7 in decimal)

Bitwise XOR (^):

Performs a bitwise XOR (exclusive OR) operation between corresponding bits of two operands.

If the bits are different, the result bit is set to 1. If they are the same, the result bit is set to 0.

int a = 5;   // binary: 0000 0101
int b = 3;   // binary: 0000 0011
int result = a ^ b;   // binary result: 0000 0110 (6 in decimal)

Bitwise Complement (~):

Inverts all the bits of the operand, changing 0s to 1s and 1s to 0s.

int a = 5;   // binary: 0000 0101
int result = ~a;   // binary result: 1111 1010 (-6 in decimal)

Left Shift (<<):

Shifts the bits of the first operand to the left by a specified number of positions.

Zeroes are shifted into the rightmost positions, and the leftmost bits that are shifted out are discarded.

int a = 5;   // binary: 0000 0101
int result = a << 2;   // binary result: 0001 0100 (20 in decimal)

Right Shift (>>):

Shifts the bits of the first operand to the right by a specified number of positions.

The sign bit (the leftmost bit) is used to fill the vacant positions from the left in signed integers (arithmetic right shift).

int a = -8;   // binary: 1111 1000 (negative number)
int result = a >> 2;   // binary result: 1111 1110 (-2 in decimal)

Bitwise operators are commonly used in low-level programming, such as dealing with binary data, optimizing performance, or implementing certain algorithms where manipulating individual bits is necessary.