Bitwise Operators in Java:
Bitwise operators perform operations bit by bit on integer types (int, long, short, byte). These operators treat values as a series of binary bits, rather than decimal numbers.
They are mostly used in low-level programming, flags, masks, and performance-critical logic
Note (for -5 >>> 1):
Even though -5 is a negative number, >>> treats it as an unsigned 32-bit binary number, filling zeros from the left. This causes a large positive value to appear as the result:
-5 in binary: 11111111 11111111 11111111 11111011
After >>> 1: 01111111 11111111 11111111 11111101
Decimal result: 2147483645
So:
System.out.println(-5 >>> 1); // prints 2147483645
List of Bitwise Operators
| Operator | Name | Description | Example | Result (Binary Level) |
|---|---|---|---|---|
| & | Bitwise AND | 1 if both bits are 1 | 5 & 3 | 0101 & 0011 = 0001 → 1 |
| | | Bitwise OR | 1 if any one bit is 1 | 5 | 3 | 0101 | 0011 = 0111 |
| ^ | Bitwise XOR | 1 if bits are different | 5 ^ 3 | 0101 ^ 0011 = 0110 → 6 |
| ~ | Bitwise Complement | Inverts all bits (1 → 0, 0 → 1) | ~5 | ~0101 = 1010 → -6 |
| << | Left Shift | Shifts bits to the left (multiplies by 2n) | 5 << 1 | 0101 → 1010 → 10 |
| >> | Right Shift | Shifts bits to the right (divides by 2n) | 5 >> 1 | 0101 → 0010 → 2 |
| >>> | Unsigned Right Shift | Shifts bits right, fills 0s from left (ignores sign bit) | -5 >>> 1 | 2147483645 |
Example: Bitwise Operations in Action
class ShikshaSanchar {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
System.out.println("a & b: " + (a & b)); // 1
System.out.println("a | b: " + (a | b)); // 7
System.out.println("a ^ b: " + (a ^ b)); // 6
System.out.println("~a: " + (~a)); // -6 (2's complement)
System.out.println("a << 1: " + (a << 1)); // 10
System.out.println("a >> 1: " + (a >> 1)); // 2
System.out.println("-5 >>> 1: " + (-5 >>> 1)); // Platform dependent
}
}
Output:
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2
-5 >>> 1: 2147483645
Explanation
- &: Only where both bits are 1, result is 1. → 0101 & 0011 = 0001
- |: Where any bit is 1, result is 1. → 0101 | 0011 = 0111
- ^: Where bits are different, result is 1. → 0101 ^ 0011 = 0110
- ~: Inverts all bits. ~5 gives -6 (2's complement).
- <<: Shifts bits left by 1 → 5 << 1 = 10
- >>: Shifts bits right by 1 → 5 >> 1 = 2
- >>>: Right shifts without sign. For negative numbers, inserts 0s from the left.
Use Cases
- Bit masking & flag checks
- Cryptography & compression algorithms
- Optimizing arithmetic (like multiply/divide by 2)
Summary:
- Bitwise operators work on individual bits of integer data types.
- &, |, ^, ~ for logical bit manipulation.
- <<, >>, >>> for shifting bits.
- Use >>> carefully with negative numbers — it changes sign and may cause unexpected results.
- Efficient for performance-sensitive logic.