Boolean Logic

AND, OR, NOT and XOR; truth tables; De Morgan's laws; short-circuit evaluation and the bitwise operators built on them.

Beginner 4 min readLesson 4 of 8

Boolean logic works with only two values, true and false (1 and 0). It underlies both the hardware (logic gates are physical Boolean operators) and every if statement you write.

The core operators

ABNOT AA AND BA OR BA XOR BA NAND B
0010001
0110111
1000111
1101100
  • AND is true only when both inputs are true.
  • OR is true when at least one is.
  • XOR (exclusive or) is true when the inputs differ.
  • NAND (not-and) is universal: every other gate can be built from NAND gates alone. So can NOR.
ABAND gateA · B

Notation

OperationLogicEngineeringJava / JSPython
NOT¬AA̅!anot a
ANDA ∧ BA · Ba && ba and b
ORA ∨ BA + Ba || ba or b
XORA ⊕ BA ⊕ Ba ^ ba != b (for bools)

Laws worth knowing

LawForm
IdentityA AND 1 = A; A OR 0 = A
AnnulmentA AND 0 = 0; A OR 1 = 1
IdempotenceA AND A = A
ComplementA AND NOT A = 0; A OR NOT A = 1
Double negationNOT NOT A = A
DistributiveA AND (B OR C) = (A AND B) OR (A AND C)
De MorganNOT (A AND B) = NOT A OR NOT B
De MorganNOT (A OR B) = NOT A AND NOT B

Short-circuit evaluation

&& and || stop as soon as the answer is known:

  • a && b: if a is false, b is never evaluated.
  • a || b: if a is true, b is never evaluated.
if (user != null && user.isActive()) { ... }   // safe: no NPE when user is null
String name = input != null ? input : "guest";

Bitwise operators: Boolean logic on every bit

The same operations applied position by position to integers:

13120100a = 12
13021100b = 10
ExpressionBinaryResultCommon use
a & b10008Test or clear bits (masking)
a | b111014Set bits, combine flags
a ^ b01106Toggle bits, find differences
~a…0011−13Invert all bits
a << 11100024Multiply by 2
a >> 200113Divide by 4 (floor)

Flags pack many booleans into one integer: Unix file permissions (rwx = 4 + 2 + 1, so chmod 755), feature flags, and network header fields. More techniques: Bit manipulation.

From logic to hardware

Gates are made of transistors, and gate circuits compute anything. For example, adding two bits:

  • sum = A XOR B
  • carry = A AND B

That's a half adder. Chain full adders and you can add 64-bit numbers — the heart of the CPU's ALU. See Logic gates & circuits.

Key takeaways
  • AND, OR, NOT (and XOR) are the building blocks; NAND alone is universal.
  • De Morgan: negating AND/OR flips the operator and negates each operand.
  • && and || short-circuit, which makes null checks safe.
  • Bitwise operators apply Boolean logic to each bit; masks and flags rely on them.
  • Gates are Boolean operators in hardware; adders are made from XOR and AND.