5.5. DeMorgan’s Laws

DeMorgan’s laws were developed by Augustus De Morgan in the 1800s. They show how to handle the negation of a complex conditional.

  • not (a and b) is the same as (not a) or (not b)
  • not (a or b) is the same as (not a) and (not b)

Notice that an and is changed to an or by negation and an or to an and.

Java uses ! to indicate negation. Applying DeMorgan’s Laws to !(x < 3 && y > 2) means that this complex conditional will be true when (x >= 3 || y <= 2) and !(x < 3 || y > 2) is the same as (x >= 3 && y <= 2).

For more information about DeMorgan’s laws see http://en.wikipedia.org/wiki/De_Morgan’s_laws.

    5-5-1: What is printed when the following code executes and x equals 4 and y equals 3?

    if (!(x < 3 || y > 2)) System.out.println("first case");
    else System.out.println("second case");
    
  • first case
  • This will print if x is greater than or equal 3 and y is less than or equal 2. In this case x is greater than 3 but y is not less than or equal 2.
  • second case
  • This will print if x is less than 3 or y is greater than 2. Think of it as the negation of the negation which cancels the negation.

    5-5-2: What is printed when the following code executes and x equals 4 and y equals 3?

    if (!(x < 3 && y > 2)) System.out.println("first case");
    else System.out.println("second case");
    
  • first case
  • This will print if x is greater than or equal 3 or y is less than or equal 2. In this case x is greater than 3 so the first condition is true.
  • second case
  • This will print if x is less than 3 and y is greater than 2.
Next Section - 5.6. Common Mistakes