Java for Beginners · Module 3: Operators
🎯 Working Below the Number
Inside the computer every number is stored as a row of bits, each 0 or 1. For example, 12 is 1100. Bitwise operators work directly on these bits, one position at a time. They are fast, and they are used in networking, graphics, permissions, games and competitive programming.
1️⃣ Bitwise AND, OR, XOR, NOT
| Operator | Name | What it does | Example |
& | AND | 1 only if both bits are 1 | 12 & 10 = 8 |
| | OR | 1 if either bit is 1 | 12 | 10 = 14 |
^ | XOR | 1 if the bits differ | 12 ^ 10 = 6 |
~ | NOT | flips every bit | ~12 = -13 |
<< | left shift | multiplies by 2n | 5 << 3 = 40 |
>> | signed right shift | divides by 2n, keeps the sign | -16 >> 2 = -4 |
>>> | unsigned right shift | divides, fills with 0 | -16 >>> 28 = 15 |
Figure 4: All the bitwise and shift operators.
| A | B | A & B | A | B | A ^ B |
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Figure 2: Truth table for single bits.
Figure 1: Bitwise operators work on each bit position separately.
Program 1: Bitwise operators with binary output
public class BitwiseDemo {
public static void main(String[] args) {
int a = 12; // 1100
int b = 10; // 1010
System.out.println("a = " + a + " binary " + Integer.toBinaryString(a));
System.out.println("b = " + b + " binary " + Integer.toBinaryString(b));
System.out.println("a & b = " + (a & b) + " binary " + Integer.toBinaryString(a & b));
System.out.println("a | b = " + (a | b) + " binary " + Integer.toBinaryString(a | b));
System.out.println("a ^ b = " + (a ^ b) + " binary " + Integer.toBinaryString(a ^ b));
System.out.println("~a = " + (~a));
}
}
a = 12 binary 1100
b = 10 binary 1010
a & b = 8 binary 1000
a | b = 14 binary 1110
a ^ b = 6 binary 110
~a = -13
Integer.toBinaryStringshows a number’s bits, so you can check the working. It drops leading zeros, so 0110 appears as 110.~aflips every one of the 32 bits. For any number,~aequals-(a + 1), so~12is -13.- Do not confuse
&with&&from Lesson 13:&&joins true/false conditions, while&on numbers works on bits.
2️⃣ Shift Operators
Figure 3: Shifting moves every bit to the left or right.
Program 2: Shifting left and right
public class ShiftDemo {
public static void main(String[] args) {
int x = 5;
System.out.println("5 << 1 = " + (x << 1));
System.out.println("5 << 3 = " + (x << 3));
int y = 40;
System.out.println("40 >> 1 = " + (y >> 1));
System.out.println("40 >> 3 = " + (y >> 3));
int neg = -16;
System.out.println("-16 >> 2 = " + (neg >> 2));
System.out.println("-16 >>> 28 = " + (neg >>> 28));
}
}
5 << 1 = 10
5 << 3 = 40
40 >> 1 = 20
40 >> 3 = 5
-16 >> 2 = -4
-16 >>> 28 = 15
5 << 3is 5 × 2³ = 40. A left shift is a very fast multiplication by a power of 2.40 >> 3is 40 ÷ 2³ = 5. A right shift divides and drops the fraction.>>keeps the sign, so-16 >> 2stays negative (-4).>>>always fills with zeros, so a negative number becomes a large positive one. Here -16 >>> 28 gives 15.
3️⃣ Useful Bit Tricks
This program uses the conditional operator ? :, which Lesson 15 explains. Read (test) ? A : B as “if the test is true give A, otherwise B”.
public class BitTricks {
public static void main(String[] args) {
int n = 13;
System.out.println(n + " is " + ((n & 1) == 0 ? "even" : "odd"));
int p = 16, q = 18;
System.out.println("16 power of two? " + ((p & (p - 1)) == 0));
System.out.println("18 power of two? " + ((q & (q - 1)) == 0));
int a = 7, b = 9;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("swapped: a = " + a + ", b = " + b);
int flags = 0b0101;
boolean bit2 = (flags & (1 << 2)) != 0;
boolean bit1 = (flags & (1 << 1)) != 0;
System.out.println("bit 2 set? " + bit2 + ", bit 1 set? " + bit1);
System.out.println("hex 0xFF = " + 0xFF + ", binary 0b1010 = " + 0b1010);
}
}
13 is odd
16 power of two? true
18 power of two? false
swapped: a = 9, b = 7
bit 2 set? true, bit 1 set? false
hex 0xFF = 255, binary 0b1010 = 10
- Even or odd: the last bit of an odd number is always 1, so
n & 1gives 1 for odd and 0 for even. - Power of two: a power of two has a single 1 bit (16 is 10000). Subtracting 1 turns it into 01111, so
p & (p - 1)is 0 only for powers of two. - Swap without a temporary variable: three XORs exchange a and b, because XOR-ing a value twice with the same number brings it back.
- Test a bit:
1 << 2creates a mask with only bit 2 set. AND-ing with it checks that bit. - Literals:
0b1010writes a binary number and0xFFa hexadecimal one. Both are converted to ordinary int values.
4️⃣ Errors Beginners Meet
public class Bad1 {
public static void main(String[] args) {
double d = 5.5;
System.out.println(d & 1);
}
}
Bad1.java:4: error: bad operand types for binary operator ‘&’
System.out.println(d & 1);
^
first type: double
second type: int
1 error
- Bitwise operators accept only integer types (and boolean for
&,|,^). Adoublehas no simple bit pattern to work on this way.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Using ^ for power | ^ is XOR: 2 ^ 3 is 1 | Use Math.pow(2, 3) |
Mixing up & and && | Bits versus conditions | Use && for true/false tests |
Writing a & b == 0 | == binds tighter than & | Write (a & b) == 0 |
Expecting >> to fill with 0 on negatives | It keeps the sign bit | Use >>> |
| Applying bit operators to decimals | Not allowed | Use int or long |
❓ Frequently Asked Questions
Q1. Why use shifts instead of multiplying?
They are clear for powers of two and used in low-level code. Modern compilers already optimise normal multiplication, so choose whichever is easier to read.
Q2. What does ^ do on booleans?
It is true when exactly one side is true.
Q3. What happens if I shift by more than 31 on an int?
Java uses only the lowest 5 bits of the shift count, so x << 32 is the same as x << 0.
Q4. Are bitwise operators asked in interviews?
Yes: odd/even, power of two, swapping, counting set bits and finding a single non-repeating number are classic questions.
✅ Key Takeaways
&,|,^,~work on every bit position of whole numbers.x << nmultiplies by 2n.x >> ndivides by 2n.>>>fills with zeros.n & 1tells odd from even.p & (p - 1) == 0(with brackets) tells a power of two.- Use
Integer.toBinaryStringto see the bits. ^is XOR, not “to the power of”.
🎓 Practice questions: (1) Work out 25 & 14, 25 | 14 and 25 ^ 14 by writing the bits, then check with a program. (2) What is1 << 4? (3) Write code to count how many 1 bits are in a number. (4) What is the difference between>>and>>>for -8? (5) Explain howa ^ b ^ bgets backa.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java