Java Bitwise Operators
Overview of Bitwise Operators
Java provides six bitwise operators that allow direct manipulation of individual bits within integer types. These operators work at the binary level, providing powerful and efficient ways to perform low-level operations.
Bitwise Operator Types
Operator |
Symbol |
Description |
Example |
AND |
& |
Bitwise AND |
5 & 3 |
OR |
| |
Bitwise OR |
5 | 3 |
XOR |
^ |
Bitwise XOR |
5 ^ 3 |
NOT |
~ |
Bitwise NOT |
~5 |
Left Shift |
<< |
Shifts bits left |
5 << 1 |
Right Shift |
>> |
Shifts bits right |
5 >> 1 |
Detailed Operator Explanations
Bitwise AND (&)
The AND operator compares each bit and returns 1 if both bits are 1.
public class BitwiseAndDemo {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a & b; // Binary: 0001 (Decimal: 1)
System.out.println("Bitwise AND result: " + result);
}
}
Bitwise OR (|)
The OR operator returns 1 if at least one bit is 1.
public class BitwiseOrDemo {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a | b; // Binary: 0111 (Decimal: 7)
System.out.println("Bitwise OR result: " + result);
}
}
Bitwise XOR (^)
The XOR operator returns 1 if bits are different.
graph LR
A[XOR Truth Table] --> B[0 ^ 0 = 0]
A --> C[0 ^ 1 = 1]
A --> D[1 ^ 0 = 1]
A --> E[1 ^ 1 = 0]
Bitwise 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; // Binary: 0101
int result = a << 1; // Binary: 1010 (Decimal: 10)
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; // Binary: 1010
int result = a >> 1; // Binary: 0101 (Decimal: 5)
System.out.println("Right Shift result: " + result);
}
}
Practical Applications
Flag Management
Bitwise operators are excellent for managing boolean flags efficiently:
public class FlagManagementDemo {
public static void main(String[] args) {
final int READ_PERMISSION = 1 << 0; // 1
final int WRITE_PERMISSION = 1 << 1; // 2
final int EXECUTE_PERMISSION = 1 << 2; // 4
int userPermissions = READ_PERMISSION | WRITE_PERMISSION;
// Check if user has read permission
boolean hasReadPermission = (userPermissions & READ_PERMISSION) != 0;
System.out.println("Has read permission: " + hasReadPermission);
}
}
Learning with LabEx
At LabEx, we emphasize understanding bitwise operators as a key skill for advanced programming and system-level optimization. Mastering these operators opens up powerful techniques for efficient data manipulation.