Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
~operand

Mathematical Equivalence

Because Java represents signed integers using two’s complement, applying the bitwise complement operator to any integer n mathematically yields -(n + 1).
int n = 12;
int result = ~n; // Evaluates to -13

Bit-Level Mechanics

When applied to a 32-bit int, the operator transforms the entire 32-bit sequence, including the sign bit.
int a = 5;
// Binary of a:  00000000 00000000 00000000 00000101

int b = ~a;
// Binary of b:  11111111 11111111 11111111 11111010
// Decimal of b: -6

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).
byte x = 2;

// byte y = ~x; 
// Compilation Error: Incompatible types. Possible lossy conversion from int to byte.

int y = ~x;           // Correct: The evaluated result is an int.
byte z = (byte) ~x;   // Correct: Explicit downcast required to assign back to a byte.
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.
Master Java with Deep Grasping Methodology!Learn More