Most of the languages including C, C++, Java and Python provide the boolean type that can be either set to False or True.
Consider below programs that use Logical Not (or !) operator on boolean.
The outputs of above programs are as expected, but the outputs following programs may not be as expected if we have not used Bitwise Not (or ~) operator before.
Reason: The bitwise not operator ~ returns the complement of a number i.e., it switches each 1 to 0 and each 0 to 1. Booleans True and False have values 1 and 0 respectively.
˜being the bitwise not operator,
- The expression “˜True” returns bitwise inverse of 1.
- The expression “˜False” returns bitwise inverse of 0.
Java doesn’t allow ~ operator to be applied on boolean values. For example, the below program produces compiler error.
6: error: bad operand type boolean for unary operator '~' System.out.println(~a); ^ 7: error: bad operand type boolean for unary operator '~' System.out.println(~b); ^ 2 errors
“Logical not or !” is meant for boolean values and “bitwise not or ~” is for integers. Languages like C/C++ and python do auto promotion of boolean to integer type when an integer operator is applied. But Java doesn’t do it.
This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- GFact 22 | (2^x + 1 and Prime)
- GFact 23 | (Brocard’s problem)
- Boolean Operators - Django Template Tags
- Python Logical Operators with Examples
- Python 3 - Logical Operators
- Logical Operators on String in Python
- Python Membership and Identity Operators | in, not in, is, is not
- Python Bitwise Operators
- Python | Boolean List AND and OR operations
- Python | Print unique rows in a given boolean matrix using Set with tuples
- Python | Contiguous Boolean Range
- Python | Boolean list initialization
- Boolean Indexing in Pandas
- Python program to fetch the indices of true values in a Boolean list
- Python | Ways to concatenate boolean to string
- Python | Ways to convert Boolean values to integer
- Python | Filter list by Boolean list
- Python - False indices in a boolean list
- Scala short ==(x: Int): Boolean
- Boolean Fields in Serializers - Django REST Framework
Improved By : Rajput-Ji