• Home
• Bitwise Operators in Java

# Bitwise Operators in Java

Bitwise operators in Java allow you to perform operations on the individual bits of an integer value. These operators are often used in low-level programming, where you need to manipulate the individual bits of a value for various purposes.

There are six bitwise operators in Java:

1. & (bitwise AND) – This operator compares each bit of the first operand to the corresponding bit of the second operand, and if both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
2. | (bitwise OR) – This operator compares each bit of the first operand to the corresponding bit of the second operand, and if either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
3. ^ (bitwise XOR) – This operator compares each bit of the first operand to the corresponding bit of the second operand, and if the bits are different, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
4. ~ (bitwise NOT) – This operator inverts all the bits of the operand.
5. << (left shift) – This operator shifts the bits of the first operand to the left by the number of positions specified in the second operand. The leftmost bits are lost, and the rightmost bits are filled with 0s.
6. (right shift) – This operator shifts the bits of the first operand to the right by the number of positions specified in the second operand. The rightmost bits are lost, and the leftmost bits are filled with the value of the sign bit.

Here are some examples of how these operators can be used:

``````int x = 7; // 111
int y = 4; // 100

int z = x & y; // 100 (4)

z = x | y; // 111 (7)

z = x ^ y; // 011 (3)

z = ~x; // -8 (1000 in 2's complement)

z = x << 2; // 28 (11100)

z = x >> 1; // 3 (011)``````

It’s important to note that the bitwise operators only work on integer types (byte, short, int, and long). They cannot be used with floating-point types or boolean values.