Cleanest way to toggle a boolean variable in Java?

前端 未结 9 919
悲哀的现实
悲哀的现实 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条回答
  •  -上瘾入骨i
    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)

提交回复
热议问题