Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a boolean variable switch between true and false every time a method is invoked?

Tags:

java

boolean

I am trying to write a method that when invoked, changes a boolean variable to true, and when invoked again, changes the same variable to false, etc.

For example: call method -> boolean = true -> call method -> boolean = false -> call method -> boolean = true

So basically,

if (a = false) { a = true; } if (a = true) { a = false; } 

I am not sure how to accomplish this, because every time I call the method, the boolean value changes to true and then false again.

like image 966
aperson Avatar asked Mar 19 '10 16:03

aperson


People also ask

How do you toggle between true and false?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How do you change a Boolean value from false to true?

Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.

Can you switch on a boolean?

The switch statement is one of the more syntactically complicated expressions in Java. The expression in the switch statement must be of type char, byte, short, or int. It cannot be boolean, float, double, or String.

How do I switch between true and false in Python?

Convert bool to string: str() You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .


2 Answers

value ^= true; 

That is value xor-equals true, which will flip it every time, and without any branching or temporary variables.

like image 136
ILMTitan Avatar answered Oct 08 '22 16:10

ILMTitan


Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable; 

This flips the variable.

like image 41
JoePasq Avatar answered Oct 08 '22 16:10

JoePasq