CKTIS / Java
Bitwise complement operator ~
The unary ~ operator flips every bit of an integral value after numeric promotion. Its result has type int or long. It is not the logical complement operator !: ~ does not accept boolean values.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
~expressionThe operator ~expression changes every 0 bit to 1 and every 1 bit to 0. It flips all 32 bits of an int or all 64 bits of a long, not just the visible digits of a binary literal. The identity ~x == (-x) - 1 holds under Java integer arithmetic.
The operand’s static type must be an integral primitive type (byte, short, char, int, or long) or a type that can be unboxed to one of them. For example, ~x is valid when x has type T declared as <T extends Integer>. Unary numeric promotion first unboxes the operand if needed, then promotes byte, short, and char to int. The types int and long remain unchanged. Unboxing null throws NullPointerException.
Do not confuse ~ with !, which negates a boolean value. The types boolean, float, and double are not allowed for ~. The expression ~x alone does not modify the variable x.
In the example, x is promoted from byte to int, so ~x produces -6, not a positive eight-bit value. The mask & 0xFF keeps only the lowest eight bits, producing 250 as an int.
Examples
public class Main {
public static void main(String[] args) {
byte x = 5;
int inverted = ~x;
int lowByte = inverted & 0xFF;
System.out.println(inverted);
System.out.println(lowByte);
}
}Result
-6 250
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.