Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean operation trick

Tags:

java

boolean

I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.

It's basically a one liner for this:

if (myVar) {  
    myVar = false;  
} else {  
    myVar = true;  
}  

It's something like this, but don't know what it's called or the correct syntax of it:

myVar = myVar : false ? true;
like image 798
dime Avatar asked Sep 10 '10 18:09

dime


People also ask

How do you perform a Boolean operation?

Boolean Operators are simple words (AND, OR, NOT or AND NOT) used as conjunctions to combine or exclude keywords in a search, resulting in more focused and productive results. This should save time and effort by eliminating inappropriate hits that must be scanned before discarding.

What are 5 common Boolean searches?

Boolean operators are specific words and symbols that you can use to expand or narrow your search parameters when using a database or search engine. The most common Boolean operators are AND, OR, NOT or AND NOT, quotation marks “”, parentheses (), and asterisks *.

What are the 3 types of Boolean operations?

They connect your search words together to either narrow or broaden your set of results. The three basic boolean operators are: AND, OR, and NOT.

What is the Boolean strategy?

Boolean searching allows the user to combine or limit words and phrases in an online search in order to retrieve relevant results. Using the Boolean terms: AND, OR, NOT, the searcher is able to define relationships among concepts. OR. Use OR to broaden search results.


3 Answers

How about

myVar = !myVar

?

like image 105
Alexander Rautenberg Avatar answered Nov 02 '22 17:11

Alexander Rautenberg


myVar = myVar ? false : true; is using the conditional operator.

You can just do this though

myVar = !myVar;
like image 37
nos Avatar answered Nov 02 '22 18:11

nos


Another option is XOR:

myVar ^= true;

It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.

like image 17
Mark Peters Avatar answered Nov 02 '22 17:11

Mark Peters