The Bitwise AND Operator (&)
What you'll learn: How the bitwise AND operator (&) compares bits from two integers and produces a result based on matching 1s.
How Bitwise AND Works
The bitwise AND operator (&) examines each pair of corresponding bits in two integer values. For each bit position, it returns 1 only when both bits are 1. If either bit (or both) is 0, the result for that position is 0.
Think of it like a strict gatekeeper: both bits must say "yes" (be 1) for the result to be "yes" (1).
The Bit-by-Bit Rule
Here's the simple truth table for a single bit position:
Bit A | Bit B | A & B
-------|---------|--------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1
Example with Integers
Let's see how 12 & 10 works:
int a = 12; // Binary: 1100
int b = 10; // Binary: 1010
int result = a & b;
// Bit-by-bit comparison:
// 1100 (12)
// & 1010 (10)
// ------
// 1000 (8)
System.out.println(result); // Outputs: 8
Each bit position is compared independently. Only the second bit from the left has 1 in both numbers, so only that bit is 1 in the result.
Common Uses
The & operator is often used to:
- Check if specific bits are set
- Clear certain bits in a value
- Create bit masks for flags or permissions
Key Takeaway: The bitwise AND operator (&) compares corresponding bits and returns 1 only when both input bits are 1; otherwise, it returns 0.