Boolean Expressions

Sure, boolean variables are nice. Boolean expressions are even better. Below are a couple of examples.

Is one greater than two?
1 > 2
Of course not, so the answer is false.

Is two greater than one?
2 > 1
It is, so it must be true!

Is X greater than two?
x > 2
We can’t answer this until we know the value of x!

int x = 0;
boolean isXGTRThan = x > 2; // what's the value of isXGTRThan?

x = 2013;
isXGTRThan = x > 2// what's the value of isXGTRThan?

There are a number of operators that can be used in Boolean expression:

  • greater than: >
  • less than: <
  • equal to: ==
  • greater than or equal to: >=
  • less than or equal to: <=
int x = 5;

boolean expression = x > 2;
x = 3;

expression = x < 4; // what's the value of expression?
x = x; // what's the value of x?
expression = 5 >= x; // what's the value of expression?
expression = x == x; // what's the value of x and expression?

We can build even larger Boolean expressions with logical conjunctions and disjunctions.

  • The conjunction operator is: &&. This denotes a logical ‘and’.
  • The disjunction/disjoint operator is: ||. This denotes a logical ‘or’.
boolean one = true;
boolean two = true;
boolean three = false;

boolean expression = one && two; // what is the value of expression?

expression = one || three; // what is the value of expression?

expression = one && three; // what is the value of expression?

Let’s see how well you know this stuff. 🙂

boolean expression = ((true && false) || (3 < 2)); // what's the value of expression?

-> Branching Statements