Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of double tilde (~~) in Java?

People also ask

What is double tilde?

The “double tilde” (~~) operator is a double NOT Bitwise operator. Use it as a substitute for Math. floor(), since it's faster.

What does tilde mean in Java?

The Tilde ( ~ ) performs a bitwise complement of a numerical value in Java.

How does double tilde work in Javascript?

It hides the intention of the code. It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.


In Java, it means nothing.

But that comment says that the line is specifically for GWT, which is a way to compile Java to JavaScript.

In JavaScript, integers are kind of like doubles-that-act-as-integers. They have a max value of 2^53, for instance. But bitwise operators treat numbers as if they're 32-bit, which is exactly what you want in this code. In other words, ~~hash says "treat hash as a 32-bit number" in JavaScript. Specifically, it discards all but the bottom 32 bits (since the bitwise ~ operators only looks at the bottom 32 bits), which is identical to how Java's overflow works.

If you didn't have that, the hash code of the object would be different depending on whether it's evaluated in Java-land or in JavaScript land (via a GWT compilation).