2

The one main thing I want to avoid while Java programming is excessive boolean variable declarations like this:

public static boolean mytruebool = true, myfalsebool = false, myothertruebool = true, myotherfalsebool = false;

Is there an efficient way (perhaps w/ array usage) of declaring and assigning variables? Any help is greatly appreciated!

T145
  • 1,415
  • 1
  • 13
  • 33

3 Answers3

5

If these are fields (static or otherwise), boolean will have an initial value of false. At that point, you set them according to the needs of your program. So at least, you don't have to worry about half of your boolean fields.

If you're discovering that you have too many boolean fields, then you may want to reconsider the design of your program instead of pre-initializing your values.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 2
    +1 for the second paragraph, -1 for the first. There's no gain in letting scalar fields be initialized to their default values and writing code that assumes that they'll be initialized that way. You save six or seven bytes in your source file, that's all. But you confuse readers who may not be completely familiar with Java's rules about default initialization. – ajb Feb 04 '14 at 17:22
  • 2
    @ajb if you will work with Java, you should understand the basics of Java at least, like field default values, so IMO I don't have any objection by just letting the fields *uninitialized* unless it is a priority to always give them an initial value. As an example, do you always write your entity classes with an initial value different from the default Java value for all the fields in it? – Luiggi Mendoza Feb 04 '14 at 17:27
  • @LuiggiMendoza I'm not sure I understand your last question. But if the code in my class depends on the fact that an `int` field starts out as 0, then I write an explicit initializer. If the code will always do some other assignment to it before it reads it, then I don't. Similarly for booleans, references, etc. – ajb Feb 04 '14 at 17:31
  • @ajb for example, you have this `Person` class with `String firstName`, `String middleName`, `String lastName`, `Date birthDate` and `String email` attributes (just to mention those, there can be plenty others), would you initialize all these fields in your code, in all other entity classes in your application, even knowing that some classes may have 30 or more fields? Seriously? – Luiggi Mendoza Feb 04 '14 at 17:33
  • @ajb: The fact that those fields start at those initial values are guaranteed by the JVM, but I don't disagree that adding that extra bit of information can be helpful - but, that's only if there's a handful of fields. I take references in a different light (sometimes eager initialization of a collection is better), but I shouldn't be overly worried that Oracle will forget to honor the initial value contract. Although it has happened before (with arrays). – Makoto Feb 04 '14 at 17:33
2

If you are comfortable with bit manipulation, you can store all your booleans as a single integer. In this case, you can store your initial state (and other various states) of all the "variables" as a single integer value.

boolean firstVar = false;
boolean secondVar = true;
boolean thirdVar = true;

...can become...

public class Test {

    public static final int INITIAL_STATE = 6;
    private static int myVar = INITIAL_STATE;



    public static boolean getVar(int index) {
        return (myVar & (1 << index)) != 0;
    }



    public static void setVar(int index, boolean value) {
        if (value) {
            myVar |= (1 << index);
        } else {
            myVar &= ~(1 << index);
        }
    }



    public static void printState() {
        System.out.println("Decimal: " + myVar + "  Binary: " + Integer.toBinaryString(myVar));
    }



    public static void main(String[] args) {
        System.out.println(getVar(0)); // false
        System.out.println(getVar(1)); // true
        System.out.println(getVar(2)); // true
        printState();

        setVar(0, true);
        System.out.println(getVar(0)); // now, true
        printState();
    }
}

Learn more about bit manipulation here: Java "Bit Shifting" Tutorial?

Community
  • 1
  • 1
martinez314
  • 12,162
  • 5
  • 36
  • 63
  • Very cool! How are variable values altered? What happens when myVar is edited? (the INITIAL_STATE constant probably isn't needed since it's value is that of myVar; simply making myVar public would give a level of external editing)? – T145 Feb 04 '14 at 17:59
  • @T145 Correct, INITIAL_STATE isn't necessary. But if you had various states of all your booleans that you may want to assign at various times, then storing them as constants will be useful. – martinez314 Feb 04 '14 at 18:51
  • How would I make it so that all of the values are true by default? – T145 Feb 04 '14 at 19:11
  • @T145 -1 or ~0 (that's a tilde) will work. Read up on bitwise operations to learn why this is the case. – martinez314 Feb 04 '14 at 19:17
  • In place of 6, @whiskeyspider? – T145 Feb 04 '14 at 19:19
0

This should work ; tested already;

      boolean mytruebool,myothertruebool;
      mytruebool = myothertruebool= true;

      boolean myfalsebool,myotherfalsebool;
      myfalsebool=myotherfalsebool=false;
z atef
  • 7,138
  • 3
  • 55
  • 50
  • This will not work at the class scope level, which the `public static` modifiers imply. There would need to be an init() method involved, or some other means for initialization of the variables. The declaration part would be fine. – turbo Feb 04 '14 at 17:26
  • 1
    If this is strictly public static , then you are right . else @T145 can still assign locally declared Boolean variables this way semi-bulk lol . – z atef Feb 04 '14 at 17:34
  • I typically try to avoid doing this because: a) it's inefficient for mutable objects b) most Java developers consider it opposite of being visually simple c) if you do it enough, it gets hard to keep track of what's what. – T145 Feb 04 '14 at 17:56