|
The bitwise complement operator is applied to operands of integral datatypes (byte, short, char, int, long) only. Java has a bit representation for integral primitives. It means that it internally uses bit patterns to represent integral values. For instance, a byte value 2 is represented as 00000010.
|
|
The bit representation is unique within the JVM for a given value of particular type. The actual memory allocation for storing these values is very much platform dependent. But you need not worry about it as the bit representation itself is always platform independent. For instance, the byte value 2 is always represented as 00000010 on any of the platforms Java runs. |
The bitwise complement operator ~ works on the bit representation of operand. When applied, it coverts all 0s into 1s and all 1s into 0s in the bit representation. In short, it inverts the bits. Therefore it is also known as bitwise inversion operator. If you apply it to a byte value 2, the result is calculated by inverting bits in 00000010. Therefore, the bit representation of result is 11111101. The following code applies ~ to 2 to get a value –1.
byte c = ~2; // Value of c is –1. (Bit representation 11111101)
You may recall that in chapter 7 (Primitives and Arrays) we learned that the bit representation of negative numbers has its MSB (most significant bit) 1. Since the inversion operator always inverts 0 to 1 and 1 to 0, it always changes the sign of its operand. In fact, if operand x is any integral primitive, the value of ~x is always (-x)-1.