Skip to content

DeMorgan's Law

  • Lesson
  • 2 min read
  • 5 of 5 in this chapter

DeMorgan's??

Welcome to one of the most painful things in AP Computer Science A: DeMorgan's Law.

It's not painful, just really really tedious. But we'll go through it simply.

You already know these logical operators:

  • && - AND
  • || - OR
  • ! - NOT

And they make sense. If they don't, please review the previous lesson. Here's a quick review:

If we use &&, both of the options need true for the entire expression to be true.

If we use ||, only one of the options needs to be true for the entire expression to be true.

If we use !, we can invert a value from true to false, along with checking if something isn't equal to another thing.

The Law

Let's use some pseudocode to explain DeMorgan's Law. pseudocode is code that doesn't run but allows us to understand the logic.

If we wrote X and Y, the conditional only works if X and Y are true.

If we wrote X or Y, the conditional only works if X or Y is true.

Now, let's add not.

We end up with: not(X and Y) and not(X or Y)

Rule #1 - not(X and Y)

DeMorgan's Law is all about breaking up the statement above (or piecing it together).

And simply, here's all you need to know:

not(X and Y) is the same as not X or not Y

Rule #2 - not(X or Y)

The same applies for not(X or Y).

not(X or Y) is the same as not X and not Y

Remember!

And we can test these out via code:

Java
boolean x = true;
boolean y = true;

System.out.println(!(x && y));
System.out.println(!x || !y);

System.out.println(!(x || y));
System.out.println(!x && !y);

If you think about it, the way we speak is what's reflected in DeMorgan's Law.

"I do not want apples and oranges." is the same as "I do not want apples or do not want oranges." "I do not want apples or oranges." is the same as "I do not want apples and do not want oranges."

But what you need to remember is this: not(X and Y) is NOT equal to not X and not Y

image