Bitwise
- Java course
- Beginner
- Lesson 27/116
- 4 min
Learn &, |, ^, ~, <<, >> bitwise operators.
Bitwise operators
Bitwise operators work on the binary representations of numbers: & (and), | (or), ^ (xor), ~ (not), << (left shift), >> (right shift).
int a = 5; // 0101
int b = 3; // 0011
System.out.println(a & b); // 1 (0001)
System.out.println(a | b); // 7 (0111)
System.out.println(a ^ b); // 6 (0110)They are typically used in low-level programming, masking and flag operations. Everyday programs rarely need them.
Practice Use bitwise and operator
Write a Main class with a main method. Assign 5 to int a and 3 to int b. Print a & b and a | b with println.
Sample solution
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 3;
System.out.println(a & b);
System.out.println(a | b);
}
}Expected output
1 7
Shift operators
<< and >> shift bits. a << n shifts the bits of a left by n positions; each shift multiplies by two.
int a = 1;
System.out.println(a << 3); // 8 (1 * 2^3)
System.out.println(16 >> 2); // 4 (16 / 2^2)These operators can be used for fast multiply/divide, but modern compilers do this automatically. To keep code readable, prefer * and /.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the result of 5 & 3?
- 7
- 1
- 6 Correct answer
- 0
Explanation: 5 (0101) ^ 3 (0011) = 6 (0110).
2 Match the bitwise operators
| Term | Meaning |
|---|---|
& |
And |
| |
Or |
^ |
Xor |
~ |
Not |
3 Complete the bitwise or operator
int result = 5 ____ 3;
int result = 5 | 3;
Explanation: Bitwise or uses |.