Demonstrate Bitwise OR in Java
Problem
The bitwise OR operator (|) compares two numbers bit by bit, producing a 1 in each position where either operand has a 1 there — it only produces a 0 where both operands have a 0.
Given two integers, compute their bitwise OR and show the binary representation of both operands and the result.
Java Program
public class DemonstrateBitwiseOr {
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 wherever either input bit is 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 = 1, position 1 is0 | 1 = 1, position 0 is0 | 0 = 0, giving1110. - 4
1110in binary is14in decimal, which is whata | bevaluates to.
12 (1100) OR 10 (1010) keeps every bit position where either operand has a 1 — positions 3, 2, and 1 — giving 1110, or 14.Key Point: Bitwise OR is the standard way to set a specific bit without disturbing the others — n | (1 << k) turns on bit k of n while leaving every other bit exactly as it was.
Key Concepts
Approach 2: Java 8
import java.util.function.IntBinaryOperator;
public class BitwiseOrLambda {
public static void main(String[] args) {
int a = 12;
int b = 10;
// The | logic is stored as a named, reusable lambda
IntBinaryOperator or = (x, y) -> x | y;
int result = or.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 'OR these two ints' into a reusable value instead of a one-off inline expression.
- 1
IntBinaryOperator or = (x, y) -> x | y;stores the bitwise OR logic as a lambda. - 2
or.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, or.applyAsInt(12, 10) returns 14, same as a | b.Key Point: Naming the lambda or makes it clear at the call site what operation it performs — the same pattern used for the arithmetic and relational operator pages.