Demonstrate Bitwise NOT in Java
Problem
The bitwise NOT operator (~) flips every bit of its operand, including the sign bit — because Java stores integers in two's complement form, flipping every bit of a positive number always produces a negative result.
Given an integer, compute its bitwise complement and explain why the result is negative.
Java Program
public class DemonstrateBitwiseNot {
public static void main(String[] args) {
int a = 5;
int result = ~a; // flips every bit, including the sign bit
System.out.println("a = " + a + " (" + String.format("%32s", Integer.toBinaryString(a)).replace(' ', '0') + ")");
System.out.println("~a = " + result);
}
}Output
Core Logic
Flipping every one of a's 32 bits — not just the visible ones — turns the leading 0 (positive sign) into a 1 (negative sign), which is why the result comes out negative.
- 1
Integer.toBinaryString(a)shows all 32 bits of5, mostly leading zeros:00000000000000000000000000000101. - 2
~aflips every single one of those 32 bits — each0becomes1and each1becomes0, including the ones that looked like leading zeros. - 3Flipping the leading bit from
0to1makes the result negative, since Java'sintuses two's complement, where the leading bit is the sign bit. - 4The identity
~n == -(n + 1)gives the decimal result directly without needing to read out all 32 flipped bits:~5 == -(5 + 1) == -6.
a = 5: every bit flips, the sign bit included, giving the two's complement bit pattern for -6 — matching -(5 + 1).Key Point: ~n always equals -(n + 1) for any int — that identity is faster to compute by hand than tracing through all 32 flipped bits, and it's exactly why ~0 is -1, not some large positive number.
Key Concepts
Approach 2: Java 8
import java.util.function.IntUnaryOperator;
public class BitwiseNotLambda {
public static void main(String[] args) {
int a = 5;
// The ~ logic is stored as a named, reusable lambda
IntUnaryOperator not = x -> ~x;
int result = not.applyAsInt(a);
System.out.println("a = " + a + " (" + String.format("%32s", Integer.toBinaryString(a)).replace(' ', '0') + ")");
System.out.println("~a = " + result);
}
}
Output
Core Logic
Wrapping ~ in a named IntUnaryOperator turns 'complement this int' into a reusable value instead of a one-off inline expression.
- 1
IntUnaryOperator not = x -> ~x;stores the bitwise complement logic as a lambda. - 2
not.applyAsInt(a)calls it witha, returning the same result~awould inline. - 3The 32-bit binary string is built exactly as before, padded with
String.format().
a = 5, not.applyAsInt(5) returns -6, same as ~a.Key Point: Naming the lambda not makes it clear at the call site what operation it performs — the same pattern used for the other bitwise operator pages, just with one operand instead of two.