Bitwise & Shift Operators in Java
A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1.
| Operator | Description | Example | Explanation |
|---|---|---|---|
| & | Bitwise AND | 5 & 3 | Performs AND operation on each bit (1 if both bits are 1) |
| | | Bitwise OR | 5 | 3 | Performs OR operation on each bit (1 if any bit is 1) |
| ^ | Bitwise XOR (exclusive OR) | 5 ^ 3 | Performs XOR on each bit (1 if bits differ) |
| ~ | Bitwise NOT (One's complement) | ~5 | Inverts each bit (0 → 1 and 1 → 0) |
| << | Left Shift | 5 << 1 | Shifts bits left, fills right with 0 (multiplies by 2n) |
| >> | Signed Right Shift | 5 >> 1 | Shifts bits right, fills left with sign bit (preserves sign) |
| >>> | Unsigned Right Shift | -5 >>> 1 | Shifts bits right, fills left with 0 (does not preserve sign) |

Code Snippet
//Bitwise & Shift Operators in Java
public class App {
public static void main(String[] args) {
// Bitwise Operators
int a = 5; // binary: 0101
int b = 3; // binary: 0011
System.out.println("Bitwise AND (5 & 3): " + (a & b)); // 1 (0001)
System.out.println("Bitwise OR (5 | 3): " + (a | b)); // 7 (0111)
System.out.println("Bitwise XOR (5 ^ 3): " + (a ^ b)); // 6 (0110)
System.out.println("Bitwise NOT (~5): " + (~a)); // -6 (two's complement)
// Shift Operators
int c = 5; // 0000 0101
System.out.println("Left shift (5 << 1): " + (c << 1)); // 10 (0000 1010)
System.out.println("Signed right shift (5 >> 1): " + (c >> 1)); // 2 (0000 0010)
int d = -10; // negative number example
System.out.println("Signed right shift (-10 >> 1): " + (d >> 1)); // -5 (fills with sign bit)
System.out.println("Unsigned right shift (-10 >>> 1): " + (d >>> 1)); // Large positive number (fills with 0)
}
}