Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most concise way to get the inverse of a Java boolean value? [duplicate]

If you have a boolean variable:

boolean myBool = true; 

I could get the inverse of this with an if/else clause:

if (myBool == true)  myBool = false; else  myBool = true; 

Is there a more concise way to do this?

like image 903
faq Avatar asked Oct 11 '10 14:10

faq


People also ask

How do you return the opposite of boolean?

The ! is a logical operator that will convert a value to its opposite boolean. Since JavaScript will coerce values, it will “convert” a value to its truthy/falsey form and return the opposite boolean value. When we perform the ! operation on a number other than 0 it, returns false .

How can I return two boolean values in Java?

You can change your return type to boolean[] so that you can return 2 boolean values. Show activity on this post. "return" terminates your method and returns the value. Everything below return is not reachable.

Can you compare two boolean values in Java?

We use the compare() method of the BooleanUtils class to compare two boolean values. The method takes two values and returns true if both the values are the same. Otherwise, it returns false .


1 Answers

Just assign using the logical NOT operator ! like you tend to do in your condition statements (if, for, while...). You're working with a boolean value already, so it'll flip true to false (and vice versa):

myBool = !myBool; 
like image 156
BoltClock Avatar answered Oct 07 '22 17:10

BoltClock