When you execute ~4, keep in mind that "4" is an int, which is 32 bits. 4 is this:
00000000 00000000 00000000 00000100
When you complement that, you get this:
11111111 11111111 11111111 11111011
Because the sign bit is a 1, we know this is a negative number. To see what number that is, we flip the bits and add one:
00000000 00000000 00000000 00000100 (bits flipped)
00000000 00000000 00000000 00000101 (added 1)
That final value is 5, so our negative number was -5.
More info here:
Negative Numbers in Java - Two's Complement Also, from the JLS,
15.15.5 Bitwise Complement Operator ~:
At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, ~x equals (-x)-1.
[ June 26, 2008: Message edited by: Corey McGlone ]