liveBook · Manning

De Morgan's laws

As explained in 100 Java Mistakes and How to Avoid Them

De Morgan's laws state that negating a disjunction is equivalent to conjoining the negated operands, and negating a conjunction is equivalent to disjoining them.

De Morgan's laws explain how negation changes Boolean operators: !(a || b) equals !a && !b, while !(a && b) equals !a || !b. Applying the transformation requires changing both the negation of each operand and the operator. section 2.8

Use the laws to avoid conditions that silently accept invalid values or process the wrong branch:

  • Review impossible range checks such as byteValue < 0 && byteValue > 255; no value can satisfy both comparisons. section 2.8
  • When excluding either of two alternatives, preserve the grouped negation or change || to && and negate both operands. section 2.8
  • Prefer parentheses when they make the intended logic clearer, especially in conditions combining exclusions and ranges. section 2.8

Correcting a printable-character check

The faulty condition uses && between c < 0x20 and c > 0x7E, so it can never reject characters outside the printable range. The corrected condition uses (c < 0x20 || c > 0x7E), while separately allowing tab and newline. section 2.8

void processLine(String line) {
  // Ignore comments
  if (!line.startsWith("#") || !line.startsWith("//")) {
    processContentLine(line);
  }
}

Inspect the treacherous manually negated condition: with mutually exclusive prefixes, !startsWith("#") || !startsWith("//") is always true, so comment lines are not skipped. section 2.8

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains both equivalences through focused Java failures and corrected conditions, then notes limits of static analysis.
Examples
Uses byte-range validation, printable ASCII detection, and comment-line filtering as concrete failure cases.
What it assumes
Assumes familiarity with Java comparisons, Boolean operators, negation, and conditional statements.
What you can do after
Diagnose impossible or always-true conditions and rewrite manually negated Java expressions correctly.
How it connects
Connects Boolean logic with range validation, conditional branches, printable-character checks, and static analysis.

Also explained in

Compare how 2 books explain De Morgan's laws →

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.