Bitwise Operators
Bitwise operators work directly on the binary representation of integers. They are fundamental for low-level programming, optimization, and many algorithmic problems. Java provides six bitwise operators.
1. AND (&) – Sets each bit to 1 if both bits are 1.
2. OR (|) – Sets each bit to 1 if at least one bit is 1.
3. XOR (^) – Sets each bit to 1 if bits are different.
4. NOT (~) – Inverts all bits (unary).
5. Left Shift (<<) – Shifts bits left, fills with 0 (multiplies by 2).
6. Right Shift (>>) – Shifts bits right, fills with sign bit (divides by 2).
7. Unsigned Right Shift (>>>) – Shifts right, fills with 0.
Examples:
int a = 5; // 0101
int b = 3; // 0011
int and = a & b; // 0001 = 1
int or = a | b; // 0111 = 7
int xor = a ^ b; // 0110 = 6
int not = ~a; // ...11111010 (two's complement)
int left = a << 1; // 1010 = 10
int right = a >> 1; // 0010 = 2
Two Minute Drill
- &, |, ^, ~, <<, >>, >>> are the bitwise operators.
- Useful for low-level programming, flags, and optimization.
- Shift operators are often used to multiply/divide by powers of two.
- Understanding binary representation is key.
Need more clarification?
Drop us an email at career@quipoinfotech.com
