I just started learning programming in Java. I made a program which calculates the complement of an integer
package demo;
public class unaryOperators {
public static void main(String[] args) {
int numOne = 10;
System.out.println(~numOne);
}
}
The program runs without any errors but the output is not as expected! The output was -11 but as far as I know, Bitwise complement operator complements all the bits of the number.
10 in decimal is 1010
So, ~10 should be 0101 i.e. 5 in decimal!
I referred some articles but cannot find one which in simple for a novice like me to understand.
Thanks for your time!
>Solution :
Java integers are stored in two’s complement. Assuming (for simplicity) that we’re storing data in one byte, 10 is
00001010
so ~10 is
11110101
If the leading bit of a two’s complement number is 1, then the number is negative, and the exact value of that number is (the negative of) its complement plus one, hence -11. You can read the details of why this format is written the way it is in the linked Wikipedia page.