Demonstrate Bitwise XOR in Java
Problem
The bitwise XOR operator (^) compares two numbers bit by bit, producing a 1 in each position where the two operands differ, and a 0 where they're the same.
Given two integers, compute their bitwise XOR and show the binary representation of both operands and the result.
Java Program
public class DemonstrateBitwiseXor {
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 exactly where the two input bits disagree.
- 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 = 0(same), position 2 is1 ^ 0 = 1(differ), position 1 is0 ^ 1 = 1(differ), position 0 is0 ^ 0 = 0(same), giving0110. - 4
0110has no meaningful leading zero, soInteger.toBinaryString()prints it as110— decimal6, which is whata ^ bevaluates to.
12 (1100) XOR 10 (1010) flags every bit position where the two operands disagree — positions 2 and 1 — giving 110, or 6.Key Point: XOR is its own inverse — applying it twice with the same value undoes it, since x ^ y ^ y always equals x. That identity is exactly what powers the classic XOR-based variable swap trick.
Key Concepts
Approach 2: Java 8
import java.util.function.IntBinaryOperator;
public class BitwiseXorLambda {
public static void main(String[] args) {
int a = 12;
int b = 10;
// The ^ logic is stored as a named, reusable lambda
IntBinaryOperator xor = (x, y) -> x ^ y;
int result = xor.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 'XOR these two ints' into a reusable value instead of a one-off inline expression.
- 1
IntBinaryOperator xor = (x, y) -> x ^ y;stores the bitwise XOR logic as a lambda. - 2
xor.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, xor.applyAsInt(12, 10) returns 6, same as a ^ b.Key Point: Naming the lambda xor makes it clear at the call site what operation it performs — the same pattern used for the arithmetic and relational operator pages.