Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a boolean value? [duplicate]

In Java (or, to be honest, any computer language), to increment an int, you do as so:

// Option 1 - efficient
int x = 0;
x++;
// x = 1

// Option 2 - works, but is ugly
int y = 0;
y = y + 1;
// y = 1;

How would you do this to a boolean?

// Standard way to
// oppose a boolean
boolean isTrue = false;
if(isTrue){
    isTrue = false;
} else if(!isTrue){
    isTrue = true;
}

Is there not a shortcut to change a boolean? For example, if the boolean was true, is there a way to change it with just a small shortcut like x++;?

like image 638
user3422952 Avatar asked Jul 22 '26 15:07

user3422952


1 Answers

You can use ! to flip its value.

isTrue = !isTrue;

! inverts the value of a boolean.

like image 86
Alexis C. Avatar answered Jul 25 '26 03:07

Alexis C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!