views:

162

answers:

2

Please let me know the difference between ~ and ! operator in java.

+4  A: 

~ is the negation operator. It negates bits from true to false or false to true. Used only with integral data types (int, short, byte, char, long).

! flips the value of a boolean. This will work on anything that will result in a logical value. So if you have foo < 5 you can do !(foo < 5) and the result will be the opposite.

Ólafur Waage
`So if you have foo < 5 you can do !(foo < 5) and the result will be the opposite` i got it :D
Rakesh Juyal
Isn't a bool stored as a byte for memory alignment purposes though?
JulianR
-1, saying that ! flips one bit is rather misleading. See tangens' answer for beter explanation.
Tuure Laurinolli
-1 It is wrong to say ! flips a bit, the internal representation isn't specified for Java. In C, which isn't as careful as Java to distinguish integers and booleans, ! maps 0 to 1 and nonzero values to 0.
starblue
Fixed, sorry, i'm from a more of a c world.
Ólafur Waage
+10  A: 

~ is a bitwise complement operator:

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

! is a logical complement operator. It inverts the value of a boolean.

tangens