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

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.

This question is related to java boolean

The answer is


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

I think that is what you are asking for??


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.


I do it with boolean = !boolean;


var logged_in = false;
logged_in = !logged_in;

A little example:

_x000D_
_x000D_
var logged_in = false;_x000D_
_x000D_
_x000D_
$("#enable").click(function() {_x000D_
    logged_in = !logged_in;_x000D_
    checkLogin();_x000D_
});_x000D_
_x000D_
function checkLogin(){_x000D_
    if (logged_in)_x000D_
        $("#id_test").removeClass("test").addClass("test_hidde");_x000D_
    else_x000D_
        $("#id_test").removeClass("test_hidde").addClass("test");_x000D_
    $("#id_test").text($("#id_test").text()+', '+logged_in);_x000D_
}
_x000D_
.test{_x000D_
    color: red;_x000D_
    font-size: 16px;_x000D_
    width: 100000px_x000D_
}_x000D_
_x000D_
.test_hidde{_x000D_
    color: #000;_x000D_
    font-size: 26px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="test" id="id_test">Some Content...</div>_x000D_
<div style="display: none" id="id_test">Some Other Content...</div>_x000D_
_x000D_
_x000D_
<div>_x000D_
    <button id="enable">Edit</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


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.


Just toggle each time it is called

this.boolValue = !this.boolValue;

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

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

value = (value) ? false : true;

Conditional (ternary) Operator.


value ^= true;

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