Cleanest way to toggle a boolean variable in Java?

前端 未结 9 820
悲哀的现实
悲哀的现实 2020-11-27 10:03

Is there a better way to negate a boolean in Java than a simple if-else?

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}
<         


        
相关标签:
9条回答
  • 2020-11-27 10:47

    There are several

    The "obvious" way (for most people)

    theBoolean = !theBoolean;
    

    The "shortest" way (most of the time)

    theBoolean ^= true;
    

    The "most visual" way (most uncertainly)

    theBoolean = theBoolean ? false : true;
    

    Extra: Toggle and use in a method call

    theMethod( theBoolean ^= true );
    

    Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.

    0 讨论(0)
  • 2020-11-27 10:50
    theBoolean = !theBoolean;
    
    0 讨论(0)
  • 2020-11-27 10:50

    If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.

    public class Util {
    
    
    public Util() {}
    public boolean flip(boolean bool) { return !bool; }
    public void sop(String str) { System.out.println(str); }
    
    }
    

    then just create a Util object Util u = new Util(); and have something for the return System.out.println( u.flip(bool) );

    If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)

    0 讨论(0)
提交回复
热议问题