What does the ~ ~ (tilde) operator do in Java?

How does the tilde operator work in Java and what does it do?

However, I have been code in Java for several years, I have not used any serious bitwise operations using Java. When I started reading about the bitwise operator, the tilde seemed interesting, and I wanted to share my little experience.

+3


source to share


1 answer


Googling about the "~" (tilde) operator in Java hasn't provided a clear explanation that newbies can understand without issue. Also, removing the bit operator questions from the Java exam with Java SE6 is the reason why some people don't learn bit mule operations. My personal opinion is that every programmer should know and understand exactly the clear operations and how to use them in software development.

In simple words, the "~" (tilde) operator is just a bit. What does it mean? Let's write some code and try:

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:

-4

      

How does 3 convert to -4? As I said, the tilde is a bit wise NOT operator. Thus, operations are performed with their binary representation. The binary representation of 3 is 11. We declared x to be an int, and theres is the 4 bytes (32 bits) allocated for x in memory. Memory representation 3 is:



00000000000000000000000000000011

      

When we execute the tilde operator on 3, all zeros in binary 3 will be 1, and they will all be 0:

11111111111111111111111111111100

      

In the JVM implementation, this is -4. If you try to do the tilde operation on -4, you get 3.

Source: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

Original post (in myblog): http://blog.adil.az/post/55588073707/what-tilde-operator-does-in-java

+14


source







All Articles