Booleans

The simplest data type!

Named after this guy

George Boole, mid 19th century English mathematician and logician

Only two values

true & false

Can also think of them as

yes & no

on & off

etc.

Used with if

if (<boolean>) {
  // do something
}

Covered in Unit 3

… and with while

while (<boolean>) {
   // do something
}

Covered in Unit 4

… and with for

for (int i = 0; <boolean>; i++) {
   // do something
}

Also covered in Unit 4

But the key thing is

They are just another kind of value.

There are three things we need to know about a data type

  1. What values can be represented?

  2. What is the syntax for writing them in our langauge?

  3. What can we do with them?

What values can be represented?

As we said before, true and false.

How do we write booleans?

true

false

That’s it.

Unlike numbers, there aren’t different ways of writing the same literal value.

What can we do with booleans?

Same as with numbers: combine them in expressions.

But the operators are different.

Three logicial operators

AND, OR, and NOT

These are the three operators defined in Boolean Algrebra by our friend George Boole.

We’re all used to using them as we saw in the warmup.

And

Writen &&

true && false

Evaluates to true if, and only if, both of its operands are true.

Or

Written ||

true || false

Evaluates to true if either, or both, operands are true.

Not

Written !

!true

Flips the logical value, true to false and false to true.

Writing expressions with all literal values (true and false) is kinda silly because we could just figure out what the value is and write that.

But they make a lot more sense when we are writing expressions in terms of variables.

Some examples

Am I hangry?

Suppose hungry is a boolean that says whether I’m hungry and angry says whether I’m angry.

What’s an expression that captures whether or not I’m hangry?

hungry && angry

Do I stay up late?

Suppose homework is a boolean that says whether I have homework to grade and newEpisodes is a boolean that says whethere there new episodes of my favorite TV show available.

What’s an expression that captures whether I will stay up late if I always stay up late to grade homework or to watch new episodes of my favorite show?

homework || newEpisodes

Am I awake?

asleep is a boolean that says whether I’m asleep.

What’s an expression that says whether I’m awake?

!asleep

tl;dr

Booleans are just another kind of value.