Search code examples
javavariablesdeclarationbulk

Is there a way to "bulk assign" boolean variables in Java?


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!


Solution

  • 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?