Skip to main content
The ~ (bitwise complement) operator is a unary operator that performs a logical negation on each individual bit of an integral data type. It evaluates the binary representation of its operand and inverts it, flipping every 0 to 1 and every 1 to 0.

Mathematical Equivalence

Because Java represents signed integers using two’s complement, applying the bitwise complement operator to any integer n mathematically yields -(n + 1).

Bit-Level Mechanics

When applied to a 32-bit int, the operator transforms the entire 32-bit sequence, including the sign bit.

Unary Numeric Promotion

The ~ operator triggers Java’s unary numeric promotion rules. If the operand is of type byte, short, or char, the Java Virtual Machine (JVM) automatically widens it to a 32-bit int before applying the bitwise inversion. Consequently, the return type of the operation is always an int (unless the operand is a long, in which case the return type remains a 64-bit long).
In the promotion example above, the 8-bit byte (00000010) is first sign-extended to a 32-bit int (00000000 00000000 00000000 00000010), and then all 32 bits are inverted. If explicitly cast back to a byte, the upper 24 bits are truncated.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More