Demonstrate Bitwise AND in Java
Problem
The bitwise AND operator (&) compares two numbers bit by bit, producing a 1 in each position only where both operands have a 1 there — everywhere else it produces a 0.
Given two integers, compute their bitwise AND and show the binary representation of both operands and the result.
Java Program
public class DemonstrateBitwiseAnd {
public static void main(String[] args) {
int a = 12;
int b = 10;
int result = a & b;
System.out.println("a = " + a + " (" + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (" + Integer.toBinaryString(b) + ")");
System.out.println("a & b = " + result + " (" + Integer.toBinaryString(result) + ")");
}
}Output
Core Logic
Lining up the binary form of both operands makes it clear that each result bit is 1 only where both input bits are 1.
- 1
Integer.toBinaryString(a)converts12into its 4-bit binary form,1100. - 2
b = 10is1010in binary. - 3
a & bcompares the two bit by bit: position 3 is1 & 1 = 1, position 2 is1 & 0 = 0, position 1 is0 & 1 = 0, position 0 is0 & 0 = 0, giving1000. - 4
1000in binary is8in decimal, which is whata & bevaluates to.
12 (1100) AND 10 (1010) keeps only the bit position where both have a 1 — position 3 — giving 1000, or 8.Key Point: Bitwise AND is the standard trick for checking or clearing specific bits — n & 1 tests whether n's lowest bit is set, which is exactly how n % 2 can be computed without division.
Key Concepts
Approach 2: Java 8
import java.util.function.IntBinaryOperator;
public class BitwiseAndLambda {
public static void main(String[] args) {
int a = 12;
int b = 10;
// The & logic is stored as a named, reusable lambda
IntBinaryOperator and = (x, y) -> x & y;
int result = and.applyAsInt(a, b);
System.out.println("a = " + a + " (" + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (" + Integer.toBinaryString(b) + ")");
System.out.println("a & b = " + result + " (" + Integer.toBinaryString(result) + ")");
}
}
Output
Core Logic
Wrapping & in a named IntBinaryOperator turns 'AND these two ints' into a reusable value instead of a one-off inline expression.
- 1
IntBinaryOperator and = (x, y) -> x & y;stores the bitwise AND logic as a lambda. - 2
and.applyAsInt(a, b)calls it withaandb, returning the same resulta & bwould inline. - 3The binary strings are built exactly as before, with
Integer.toBinaryString().
a = 12 and b = 10, and.applyAsInt(12, 10) returns 8, same as a & b.Key Point: Naming the lambda and makes it clear at the call site what operation it performs — the same pattern used for the arithmetic and relational operator pages.