Java Bitwise Operators
Overview of Bitwise Operators
Java provides six bitwise operators that allow direct manipulation of individual bits in integer types.
Bitwise Operator Types
graph TD
A[Bitwise Operators] --> B[AND &]
A --> C[OR |]
A --> D[XOR ^]
A --> E[NOT ~]
A --> F[Left Shift <<]
A --> G[Right Shift >>]
Bitwise Operator Detailed Explanation
1. Bitwise AND (&)
public class BitwiseAndDemo {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a & b; // 0001 = 1
System.out.println("Bitwise AND result: " + result);
}
}
2. Bitwise OR (|)
public class BitwiseOrDemo {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a | b; // 0111 = 7
System.out.println("Bitwise OR result: " + result);
}
}
3. Bitwise XOR (^)
public class BitwiseXorDemo {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a ^ b; // 0110 = 6
System.out.println("Bitwise XOR result: " + result);
}
}
4. Bitwise NOT (~)
public class BitwiseNotDemo {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int result = ~a; // Inverts all bits
System.out.println("Bitwise NOT result: " + result);
}
}
5. Left Shift (<<)
public class LeftShiftDemo {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int result = a << 2; // Shifts left by 2 positions
System.out.println("Left Shift result: " + result);
}
}
6. Right Shift (>>)
public class RightShiftDemo {
public static void main(String[] args) {
int a = 20; // 10100 in binary
int result = a >> 2; // Shifts right by 2 positions
System.out.println("Right Shift result: " + result);
}
}
Operator Comparison Table
Operator |
Symbol |
Description |
Example |
AND |
& |
Bitwise AND operation |
5 & 3 = 1 |
OR |
| |
Bitwise OR operation |
5 | 3 = 7 |
XOR |
^ |
Bitwise XOR operation |
5 ^ 3 = 6 |
NOT |
~ |
Bitwise NOT operation |
~5 = -6 |
Left Shift |
<< |
Shifts bits left |
5 << 2 = 20 |
Right Shift |
>> |
Shifts bits right |
20 >> 2 = 5 |
Practical Applications
- Flag management
- Bit manipulation in low-level programming
- Optimization techniques
- Cryptography and encoding
LabEx Insight
At LabEx, we emphasize understanding bitwise operators as a crucial skill for advanced Java developers, enabling more efficient and precise code manipulation.
Bitwise operations are typically faster than equivalent arithmetic operations, making them valuable in performance-critical applications.