How Does Bitwise (~) Operator Work

Ans: It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g

11110000 coverts to 00001111

The bitwise NOT operator (~) in Java is a unary operator that inverts the bits of its operand. It flips each bit of the operand from 0 to 1 and vice versa. Specifically, it performs the following steps for each bit:

  • If the bit is 0, it becomes 1.
  • If the bit is 1, it becomes 0.

It’s important to note that the bitwise NOT operation can be a bit tricky when dealing with signed integers due to Java’s two’s complement representation of negative numbers. The result of applying the bitwise NOT operation to a signed integer is the two’s complement of that number.

For example, consider the following code snippet:

java
int x = 5;
int result = ~x;
System.out.println(result);

In this case, the binary representation of 5 is 00000000 00000000 00000000 00000101. When you apply the bitwise NOT operation, you get 11111111 11111111 11111111 11111010, which is the two’s complement representation of -6 in a 32-bit signed integer.

Keep in mind that the actual result depends on the size of the data type (int, long, etc.) in terms of the number of bits used to represent the values.