Booleans: The Logic of Yes/No

Booleans: The Logic of Yes/No in Java: A power press will not close while anything is wrong, and "anything is wrong" is not a judgement the machine makes.

The Analogy: The Interlock Chain On The Press

A power press will not close while anything is wrong, and "anything is wrong" is not a judgement the machine makes. It is a chain of interlocks wired in series: the guard has to be down, the key has to be in the panel, the safety mat has to read clear, and the operator's hands have to be on both buttons. Each one of those is a genuine two-position device. There is no setting for "probably", no dial, no percentage. Either the switch is closed or it is not, and the panel reports exactly that.

Because they are wired in series, the current stops at the first open switch. The tester further down the chain is never energised and never asked. That matters more than it sounds: the mat sensor is a pressure pad that takes a moment to settle and costs something to interrogate, and it sits last in the chain precisely so that a raised guard means nobody pays for the mat reading. This is short-circuit evaluation, and in Java it is not a performance trick the compiler might apply -- it is a promise in the language specification that you are allowed to build on.

The wiring diagram also distinguishes a switch from a blank terminal. A switch reports open or closed. A terminal with nothing wired to it reports nothing at all, and an engineer who quietly reads "nothing" as "open" has made a decision the diagram does not record anywhere. Java has exactly this pair. The primitive boolean is a switch: two values, no third option, no null. The wrapper Boolean is a terminal: it can be true, it can be false, and it can be null, and the difference between those last two has caused more outages than the first two combined.

The failure mode is always about order and about honesty. Put the expensive pressure test first and every rejected cycle pays for a reading it did not need. Test the operator's hands before the guard and you have built a machine that checks the person before it checks the danger. Wire the chain in parallel so every switch is energised on every cycle, and the day one of those switches turns out to be a blank terminal, the whole panel faults on a check that never needed to run at all.


Syntax or Core Structure

A boolean holds true or false and nothing else. Comparisons produce one, the logical operators combine them, and ! inverts one.

public class Booleans {
    public static void main(String[] args) {
        boolean guardDown = true;
        boolean matClear = false;
        boolean keyIn = true;

        System.out.println("guard    " + guardDown);
        System.out.println("and      " + (guardDown && matClear));
        System.out.println("or       " + (guardDown || matClear));
        System.out.println("not      " + (!matClear));
        System.out.println("xor      " + (guardDown ^ keyIn));
        System.out.println("chain    " + (guardDown && matClear && keyIn));
        System.out.println("compare  " + (7 > 3));
        System.out.println("equalstr " + "press".equals("press"));
    }
}

Output:

guard    true
and      false
or       true
not      true
xor      false
chain    false
compare  true
equalstr true

Note what is missing. There is no conversion between numbers and booleans in either direction: if (1) does not compile, if (list) does not compile, and (boolean) 1 does not compile either. Java has no notion of a truthy value. Every condition in the language must be an expression whose type is literally boolean, which removes an entire family of bugs that C and JavaScript programmers spend years learning to avoid.


Technical Depth: What Short-Circuiting Guarantees, And What A Boolean Can Be Besides True Or False

Short-circuit versus complete evaluation

Java has two sets of logical operators, and the difference is not style. One set promises to stop early; the other promises to evaluate both sides.

OperatorEvaluates the right sideAlso works on integersTypical use
double ampersandonly when the left side is trueno, booleans onlyguarding a call that would otherwise fail
single ampersandalwaysyes, as a bitwise andwhen the right side must run for its side effect
double pipeonly when the left side is falseno, booleans onlycheap test first, expensive test second
single pipealwaysyes, as a bitwise orcombining flag bits, rarely in conditions
caretalwaysyes, as a bitwise xorexactly one of the two must hold
public class ShortCircuit {

    static int asked = 0;

    static boolean expensive(boolean answer) {
        asked++;
        return answer;
    }

    public static void main(String[] args) {
        asked = 0;
        boolean a = false && expensive(true);
        System.out.println("andand   asked " + asked + "  value " + a);

        asked = 0;
        boolean b = false & expensive(true);
        System.out.println("and      asked " + asked + "  value " + b);

        asked = 0;
        boolean c = true || expensive(false);
        System.out.println("oror     asked " + asked + "  value " + c);

        asked = 0;
        boolean d = true | expensive(false);
        System.out.println("or       asked " + asked + "  value " + d);
    }
}

Output:

andand   asked 0  value false
and      asked 1  value false
oror     asked 0  value true
or       asked 1  value true

The values agree in every pair. Only the count differs, and that count is the whole point. false && expensive(true) never calls the method, so it cannot throw, cannot block and cannot cost anything. false & expensive(true) calls it every single time. This is why if (s != null && s.length() > 0) is correct and if (s != null & s.length() > 0) throws NullPointerException on exactly the input the guard was written to survive.

The one place a single = compiles inside a condition

boolean armed = false;

if (armed = true) {
    System.out.println("branch   taken");
}
System.out.println("armed    " + armed);

Output:

branch   taken
armed    true

That block is not a typo in this lesson; it is the output of the typo. An assignment is an expression whose value is the assigned value, so armed = true evaluates to true, the branch is taken, and the variable has been silently overwritten on the way past. For every other type this is a compile error, because int n; if (n = 5) yields an int where a boolean is required. Booleans are the one case where the mistake type-checks. Comparing against the constant is unnecessary anyway: write if (armed).

Boolean is not boolean

import java.util.HashMap;
import java.util.Map;

public class Wrappers {
    public static void main(String[] args) {
        Map<String, Boolean> flags = new HashMap<>();
        flags.put("guard", Boolean.TRUE);

        Boolean guard = flags.get("guard");
        Boolean mat = flags.get("mat");

        System.out.println("guard    " + guard);
        System.out.println("mat      " + mat);
        System.out.println("safe     " + Boolean.TRUE.equals(mat));
        System.out.println("cached   " + (Boolean.valueOf(true) == Boolean.valueOf(true)));

        try {
            if (mat) {
                System.out.println("reached  yes");
            }
        } catch (NullPointerException ex) {
            System.out.println("unboxed  NullPointerException");
        }
    }
}

Output:

guard    true
mat      null
safe     false
cached   true
unboxed  NullPointerException

flags.get("mat") returns null because the key is absent, and a Map cannot tell you the difference between "stored as false" and "never stored". if (mat) has to unbox that null to get a boolean, and unboxing null throws. Boolean.TRUE.equals(mat) is the idiom that survives it: the constant is on the left, so the method call cannot be made on null, and a missing flag becomes false deliberately instead of accidentally.

The cached line prints true because Boolean.valueOf is specified to hand back the shared Boolean.TRUE and Boolean.FALSE instances, so == happens to work for autoboxed booleans. Do not build on it. A Boolean that arrives from deserialization, reflection, or the deprecated new Boolean(true) is a distinct object, and the same == then quietly returns false in production while passing every test written against literals.

parseBoolean does not validate anything

System.out.println("true     " + Boolean.parseBoolean("true"));
System.out.println("TRUE     " + Boolean.parseBoolean("TRUE"));
System.out.println("yes      " + Boolean.parseBoolean("yes"));
System.out.println("1        " + Boolean.parseBoolean("1"));
System.out.println("blank    " + Boolean.parseBoolean(""));
System.out.println("null     " + Boolean.parseBoolean(null));

Output:

true     true
TRUE     true
yes      false
1        false
blank    false
null     false

Boolean.parseBoolean is "true".equalsIgnoreCase(input) and nothing more. It never throws, not even on null, and every input it does not recognise becomes false. A configuration file that says enabled=1 or enabled=yes therefore disables the feature, silently, and the operator who wrote it has no way to discover that from the logs. Anything read from outside the program deserves a parser with a whitelist and an exception.

Precedence, and negating a compound condition

WrittenGroups asWhy it matters
not a and b(not a) and bnegation binds tighter than everything else
a and b or c(a and b) or cand binds tighter than or
a or b and ca or (b and c)the same rule surprises people the other way round
not (a and b)(not a) or (not b)De Morgan: the operator flips with the negation
not (a or b)(not a) and (not b)De Morgan again, the other direction

The two De Morgan rows are the ones that cause real bugs, because the natural mistake is to distribute the ! and leave the operator alone. !(hasKey && guardDown) means "either the key is missing or the guard is up", not "the key is missing and the guard is up". When a negated condition is doing real work, the safest move is to give it a name -- a well-named method returning boolean is cheaper to read than any amount of remembered precedence.


Real World Example: A Press That Will Not Close Unless Every Interlock Agrees

Three checks, deliberately ordered. Two of them are a lookup in a panel map and cost nothing. The third reads a pressure mat and is counted, so the output can prove it was never touched on the cycles that failed earlier.

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class Interlock {

    static int matReads = 0;

    static boolean guardDown(Map<String, Boolean> panel) {
        return Boolean.TRUE.equals(panel.get("guard"));
    }

    static boolean keyPresent(Map<String, Boolean> panel) {
        return Boolean.TRUE.equals(panel.get("key"));
    }

    static boolean matClear(Map<String, Boolean> panel) {
        matReads++;
        return Boolean.TRUE.equals(panel.get("mat"));
    }

    static boolean mayClose(Map<String, Boolean> panel) {
        return guardDown(panel) && keyPresent(panel) && matClear(panel);
    }

    static String firstFault(Map<String, Boolean> panel) {
        if (!guardDown(panel)) return "guard";
        if (!keyPresent(panel)) return "key";
        if (!matClear(panel)) return "mat";
        return "none";
    }

    static Map<String, Boolean> panel(Boolean guard, Boolean key, Boolean mat) {
        Map<String, Boolean> p = new LinkedHashMap<>();
        p.put("guard", guard);
        p.put("key", key);
        p.put("mat", mat);
        return p;
    }

    public static void main(String[] args) {
        String[] names = { "cycle-1", "cycle-2", "cycle-3", "cycle-4" };
        List<Map<String, Boolean>> panels = List.of(
                panel(true, true, true),
                panel(true, false, true),
                panel(false, true, true),
                panel(true, true, null));

        int closed = 0;
        for (int i = 0; i < names.length; i++) {
            matReads = 0;
            boolean allow = mayClose(panels.get(i));
            int reads = matReads;
            String fault = firstFault(panels.get(i));
            if (allow) {
                closed++;
            }
            System.out.println(String.format(Locale.ROOT,
                    "%-8s close %-5s fault %-5s mat reads %d",
                    names[i], allow, fault, reads));
        }

        System.out.println("cycles       " + names.length);
        System.out.println("closed       " + closed);
        System.out.println("blocked      " + (names.length - closed));
        System.out.println("null as no   " + Boolean.TRUE.equals(null));
        System.out.println("parse yes    " + Boolean.parseBoolean("yes"));
    }
}

Output:

cycle-1  close true  fault none  mat reads 1
cycle-2  close false fault key   mat reads 0
cycle-3  close false fault guard mat reads 0
cycle-4  close false fault mat   mat reads 1
cycles       4
closed       1
blocked      3
null as no   false
parse yes    false

The mat reads column is the short-circuit chain made visible. Cycle 2 stopped at the key and cycle 3 stopped at the guard, and in both cases the pressure mat was never interrogated -- not because the code checked whether it needed to, but because && guarantees the right-hand operand is not evaluated. Reordering mayClose to put matClear first would change none of the four verdicts and would double the sensor traffic on a line that rejects most cycles.

Boolean.TRUE.equals(panel.get("mat")) is the only reason cycle 4 produces a verdict instead of a stack trace. The panel is a Map<String, Boolean>, so a check that has not reported yet is null, and if (panel.get("mat")) would unbox that null and throw. Writing the constant on the left makes "no reading" mean "not clear" as a deliberate policy, and for a press that is the correct policy: absence of evidence is not permission.

mayClose and firstFault encode the same three checks in the same order, which is a real duplication rather than a stylistic one. They cannot currently disagree, but nothing stops them: the day somebody adds a fourth interlock to one method and not the other, the press will close while the report names no fault, or refuse while reporting none. The honest fix is one method -- firstFault -- and mayClose defined as firstFault(panel).equals("none"), so the two answers cannot drift apart because there is only one answer.

The limits are worth stating plainly. Reading null as false is right for a press, which fails closed, and wrong for anything that fails open: the same idiom applied to an accountLocked flag turns a missing value into "not locked" and hands out access on the strength of a database column that failed to load. matReads is a static mutable counter, which makes this program single-threaded by construction -- two presses sharing the class would report each other's readings. And the fault codes are bare strings, so "gaurd" compiles perfectly and never matches anything; an enum would make that a compile error rather than a silent shrug.


Common Mistakes

  1. Writing = where you meant ==. if (armed = true) compiles, takes the branch and overwrites the variable. Booleans are the only type where this mistake type-checks, and the cure is to drop the comparison entirely: if (armed).
  1. Using & or the single pipe in a guard. if (s != null & s.length() > 0) evaluates both sides and throws on exactly the null the guard exists to catch. Reserve the single-character operators for bit manipulation.
  1. Unboxing a Boolean that came from a map, a database row or JSON. if (flags.get("k")) throws NullPointerException when the key is absent. Use Boolean.TRUE.equals(...) or check for null first.
  1. Trusting Boolean.parseBoolean to reject nonsense. "1", "yes", "on" and "enabled" all become false with no error, so a mistyped configuration flag silently disables a feature.
  1. Comparing wrappers with ==. It works for autoboxed literals because of caching and stops working for a Boolean that arrived by deserialization. Use equals, or better, do not use Boolean at all.
  1. Expecting truthiness. if (1), if (someObject) and if (list.size()) are compile errors in Java, not shortcuts. Write the comparison out.
  1. Omitting parentheses in a mixed condition. a || b && c is a || (b && c), which is frequently not what the author meant and never obvious to the next reader.
  1. Negating a compound condition by moving the ! and leaving the operator alone. !(a && b) is !a || !b. Getting De Morgan backwards produces a condition that is wrong only for some inputs, which is the hardest kind to notice.
  1. Naming booleans badly. flag, status and check say nothing, and a negative name like notReady guarantees that somebody eventually writes !notReady. Name the true case.

Best Practices

  • Order a short-circuit chain by dependency first and cost second. The null check goes at the front because the later tests depend on it; the expensive test goes at the back because most calls will never reach it.
  • Put the constant on the left when a wrapper might be null. Boolean.TRUE.equals(value) cannot throw, and it documents that a missing value is being treated as false on purpose.
  • Use boolean everywhere internal and Boolean only where a third state genuinely exists. If null means "not answered yet", say so in the name of the variable.
  • Parse external flags with an explicit whitelist that throws. Accept a fixed set of spellings, reject everything else loudly, and let the operator find out at startup rather than in a support ticket.
  • Name a boolean as a positive assertion that reads like a sentence. isGuardDown, hasPermission and canClose all survive being negated; guardFlag does not.
  • Prefer parentheses to remembered precedence. They cost two characters and remove an entire category of review comment.
  • Return early on each failed check rather than building one enormous condition. A chain of guard clauses can tell you which check failed; a single && expression can only tell you that something did.
  • Promote a cluster of related booleans to an enum or a small type. Three flags is a condition; five flags is a state machine pretending not to be one, and it will have combinations nobody has thought about.

Practice Exercises

  1. The Sensor Bill: add a fourth interlock -- a light curtain that also increments a counter -- and run the four panels with the chain in two different orders. Print the total sensor reads for each ordering and explain from the output which ordering you would install, and what information you lose by choosing it.
  1. The Strict Parser: write static boolean parseFlag(String raw) that accepts "true", "false", "yes", "no", "1" and "0" in any case, and throws IllegalArgumentException naming the offending value for anything else. Run it against "TRUE", "Off", "" and null, and compare each result with Boolean.parseBoolean on the same input.
  1. The Single Source Of Truth: replace the String fault codes with an enum Fault { NONE, GUARD, KEY, MAT }, then redefine mayClose as firstFault(panel) == Fault.NONE so the two methods cannot disagree. Add a fifth panel where every check is null and state what the program now reports.