Bitwise Operators Explained
Introduction to Bitwise Operators
Bitwise operators manipulate individual bits of integer types, providing powerful low-level operations in Java.
Core Bitwise Operators
Bitwise AND (&)
Compares bits and returns 1 if both bits are 1.
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 in decimal)
System.out.println("Bitwise AND result: " + result);
}
}
Bitwise OR (|)
Returns 1 if at least one bit is 1.
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 in decimal)
System.out.println("Bitwise OR result: " + result);
}
}
Bitwise XOR (^)
Returns 1 if bits are different.
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 in decimal)
System.out.println("Bitwise XOR result: " + result);
}
}
Bitwise NOT (~)
Inverts all bits.
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);
}
}
Shift Operators
Left Shift (<<)
Shifts bits to the left, effectively multiplying by 2.
public class LeftShiftDemo {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int result = a << 1; // 1010 (10 in decimal)
System.out.println("Left Shift result: " + result);
}
}
Right Shift (>>)
Shifts bits to the right, effectively dividing by 2.
public class RightShiftDemo {
public static void main(String[] args) {
int a = 10; // 1010 in binary
int result = a >> 1; // 0101 (5 in decimal)
System.out.println("Right Shift result: " + result);
}
}
Bitwise Operator Comparison
Operator |
Symbol |
Description |
Example |
AND |
& |
Bitwise conjunction |
5 & 3 = 1 |
OR |
| |
Bitwise disjunction |
5 | 3 = 7 |
XOR |
^ |
Bitwise exclusive or |
5 ^ 3 = 6 |
NOT |
~ |
Bitwise negation |
~5 = -6 |
Left Shift |
<< |
Shifts bits left |
5 << 1 = 10 |
Right Shift |
>> |
Shifts bits right |
10 >> 1 = 5 |
Practical Applications
graph LR
A[Bitwise Operators] --> B[Flag Management]
A --> C[Optimization]
A --> D[Encryption]
A --> E[Low-Level Programming]
Key Takeaways
- Bitwise operators work directly on binary representations
- They are extremely efficient for low-level manipulations
- Understanding these operators is crucial for advanced programming
At LabEx, we emphasize the importance of mastering bitwise operations for comprehensive programming skills.