What "~" (tilde) operator does in Java
Googling about "~" (tilde) operator in Java didn't give a clear explanation which beginners can understand without problem. Additionally removing questions about bit-wise operators from Java exam since Java SE6 is a reason that some people don't learn bit-wise operations. My personal opinion is every programmer must know and understand clearly bit-wise operations and how to use them in software development.
In simple words the "~" (tilde) operator is just bit-wise NOT. What does it mean? Let's write a couple of code and try it:
public class Tilde { public static void main(String args[]) { int x=3; int y=~x; System.out.println(x); System.out.println(y); } }
The result will be:
3 -4
How 3 transformed to -4? As I said the tilde is bit-wise NOT operator. So the operations are performed with their binary representation. The binary representation of 3 is 11. We declared the x as int, and theres are 4 bytes (32 bits) allocated for x in memory. The representation in memory of 3 is:
00000000000000000000000000000011
When we perform a tilde operator on 3, all zeros in binary representation of 3 will be 1 and all ones will be 0:
11111111111111111111111111111100
In JVM's implementation this equals to -4. If you try to perform tilde operation on -4 you'll get 3.
Source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html












