50

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.

2
  • 3
    if that was actual code you tried, keep in mind that a = false is setting a to false, not testing it. use a == false or better yet !a to test if a boolean is false.
    – Evan Teran
    Commented Mar 19, 2010 at 16:56
  • wont that just set a = true, which then triggers the 2nd if and set a = false again. you need if else on your 2nd line
    – Horse
    Commented Aug 28, 2012 at 20:29

10 Answers 10

128
value ^= true;

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

5
  • 3
    There are usually more readable ways to do this, such as Randy's answer. Commented Aug 31, 2011 at 21:47
  • 18
    I agree it is less readable. However, I don't think it is sloppy, nor is it incorrect, the two criteria suggested for a down vote.
    – ILMTitan
    Commented Sep 1, 2011 at 15:04
  • 3
    Well, it depends. If the class' function or a significant part of it's internal state is fundamentally togglable, then yes: a toggleFoo() function is indicated, and it is probably more readable. However, if the boolean is a local variable, foo^=true is perfectly readable and doesn't clutter the class with irrelevant methods.
    – KarlP
    Commented Apr 24, 2013 at 19:22
  • 2
    never seen this kind of flip before,upvote for inspiration!
    – zionpi
    Commented Aug 27, 2015 at 6:38
  • I like it. While the traditional a=!a works pretty well (and, correct me if I'm wrong, is slightly more efficient), this is a nice alternative for variables with long names. A good way to improve readability. Commented Aug 4, 2020 at 22:57
55

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.

1
43

Just toggle each time it is called

this.boolValue = !this.boolValue;
18

Assuming your code above is the actual code, you have two problems:

1) your if statements need to be '==', not '='. You want to do comparison, not assignment.

2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe

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

Another thing that would make it even simpler is the '!' operator:

a = !a;

will switch the value of a.

3
  • 2
    The second if, if (a==true) isn't even necessary, just else suffices, unless it's a Boolean which might have a null value.
    – extraneon
    Commented Mar 19, 2010 at 16:58
  • True, but I always prefer to err on the side of being explicit in my intent, especially when answering questions such as these.
    – bobDevil
    Commented Mar 19, 2010 at 16:59
  • While the first solution is not thread-safe (2 checks), the second one is.
    – Cactusroot
    Commented May 10, 2022 at 17:03
16

I do it with boolean = !boolean;

9
value = (value) ? false : true;

Conditional (ternary) Operator.

7
var logged_in = false;
logged_in = !logged_in;

A little example:

var logged_in = false;


$("#enable").click(function() {
    logged_in = !logged_in;
    checkLogin();
});

function checkLogin(){
    if (logged_in)
        $("#id_test").removeClass("test").addClass("test_hidde");
    else
        $("#id_test").removeClass("test_hidde").addClass("test");
    $("#id_test").text($("#id_test").text()+', '+logged_in);
}
.test{
    color: red;
    font-size: 16px;
    width: 100000px
}

.test_hidde{
    color: #000;
    font-size: 26px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" id="id_test">Some Content...</div>
<div style="display: none" id="id_test">Some Other Content...</div>


<div>
    <button id="enable">Edit</button>
</div>

4
private boolean negate(boolean val) {
    return !val;
}

I think that is what you are asking for??

2

in java when you set a value to variable, it return new value. So

private boolean getValue()
{
     return value = !value;
}
0
-1

here are some ways to do it, pick the one you like:

//set a bool variable to true
bool myBool = true;
print (myBool); //:true

//set 'myBool' to not itself
myBool = !myBool;
print (myBool); //:false

//ternary myBool: if it's true return false, if it's false return true
myBool = myBool ? false : true;
print (myBool); //:true

//ternary !myBool, same as last one but inverted (because why not)
myBool = !myBool ? true : false;
print (myBool); //:false

//set myBool to not itself and true
myBool = !(myBool && true)
print (myBool); //:true

Jokes aside, I always wanted a function to call like myBool.switch() to set it to not itself and return the new value, can't find any downsides to this one. :)

2
  • Neither java code, nor does it add any value. Suggestions: 1) Not the question 2) Already stated in different answeres 3) Bad style (use !myBool) 4) Same, but even worse 5) myBool is already a boolean. Why use this and-operation?
    – Cactusroot
    Commented May 10, 2022 at 16:58
  • Can you like change one character so that I can remove the downvote? (I'll delete this comment)
    – Cactusroot
    Commented Aug 25, 2023 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.