Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ~ and ! operator?

Tags:

java

operators

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

like image 551
Rakesh Juyal Avatar asked Aug 03 '26 03:08

Rakesh Juyal


2 Answers

~ 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.

like image 158
tangens Avatar answered Aug 05 '26 18:08

tangens


~ 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.

like image 44
Ólafur Waage Avatar answered Aug 05 '26 17:08

Ólafur Waage