Bitwise operators in Java are used to perform operations at the bit level. They manipulate individual bits of integers, making them useful for low-level programming tasks like encoding, encryption, and bit manipulation.
Bitwise Operators:
1. AND (&): Sets each bit to 1 if both bits are 1.
java
int a = 5; // 0101
int b = 3; // 0011
int result = a & b; // 0001 (1 in decimal)
2. OR (|): Sets each bit to 1 if at least one of the bits is 1.
java
int result = a | b; // 0111 (7 in decimal)
3. XOR (^): Sets each bit to 1 if only one of the bits is 1.
java
int result = a ^ b; // 0110 (6 in decimal)
4. Complement (~): Inverts all the bits.
java
int result = ~a; // 1010 (in 4-bit representation, -6 in decimal)
5. Shift Operators:
– Left Shift (<<): Shifts bits to the left, filling with zeros.
– Right Shift (>>): Shifts bits to the right, preserving the sign bit.
– Unsigned Right Shift (>>>): Shifts bits to the right, filling with zeros.
Bitwise operators enhance performance in tasks that require direct bit manipulation