Java Bitwise Operators
In Java, bitwise operators are used to perform operations directly on the bits (binary representations) of numbers. They are mainly used in tasks like low-level programming, encryption, and performance optimization, where bit manipulation is needed.
These operators can be used with integer data types such as int, long, short, byte, and char. Each operation compares or modifies bits individually.
Understanding Bitwise Operation Example
Let’s take two integer variables:
a = 60 → 0011 1100 b = 13 → 0000 1101
Now, applying bitwise operations gives the following results:
a & b = 0000 1100 → 12 a | b = 0011 1101 → 61 a ^ b = 0011 0001 → 49 ~a = 1100 0011 → -61 (2's complement form)
List of Java Bitwise Operators
Operator | Description | Example |
& (AND) | Bit is 1 only if both bits are 1. | (A & B) gives 12 → 0000 1100 |
| (OR) | Bit is 1 if either bit is 1. | (A | B) gives 61 → 0011 1101 |
^ (XOR) | Bit is 1 if bits are different. | (A ^ B) gives 49 → 0011 0001 |
~ (Complement) | Inverts each bit. | (~A) gives -61 → 1100 0011 |
<< (Left Shift) | Shifts bits left, fills zeros on the right. | (A << 2) gives 240 → 1111 0000 |
| Shifts bits right, keeps the sign bit. | (A >> 2) gives 15 → 0000 1111 |
| Shifts bits right, fills with zeros. | (A >>> 2) gives 15 → 0000 1111 |
Example 1: Bitwise AND and OR Operators
public class Test {
public static void main(String[] args) {
int a = 60; // 0011 1100
int b = 13; // 0000 1101
int c = 0;
c = a & b; // AND operation
System.out.println("a & b = " + c);
c = a | b; // OR operation
System.out.println("a | b = " + c);
}
}a & b = 12 a | b = 61
Example 2: Bitwise XOR and Complement Operators
public class Test {
public static void main(String[] args) {
int a = 60; // 0011 1100
int b = 13; // 0000 1101
int c = 0;
c = a ^ b; // XOR operation
System.out.println("a ^ b = " + c);
c = ~a; // Complement operation
System.out.println("~a = " + c);
}
}a ^ b = 49 ~a = -61
Example 3: Shift Operators
public class Test {
public static void main(String[] args) {
int a = 60; // 0011 1100
int c = 0;
c = a << 2; // Left shift by 2 bits
System.out.println("a << 2 = " + c);
c = a >> 2; // Right shift by 2 bits
System.out.println("a >> 2 = " + c);
c = a >>> 2; // Zero-fill right shift by 2 bits
System.out.println("a >>> 2 = " + c);
}
}a << 2 = 240 a >> 2 = 15 a >>> 2 = 15
Summary Table
Operator | Operation | Result Example |
& | Bitwise AND | 12 |
| | Bitwise OR | 61 |
^ | Bitwise XOR | 49 |
~ | Bitwise Complement | -61 |
<< | Left Shift | 240 |
Right Shift | 15 | |
Zero-Fill Right Shift | 15 |