1 of 12

Logical Operators �&�Boolean Expressions

Lesson 6.1

2 of 12

Logical Operators in Java

  • Java programs use the following 3 logical operators�
    • AND
    • OR
    • NOT��
  • These operators are used to control the behavior of if, while, and for statements.�

3 of 12

Using AND

  • Scenario #1

If the sun is shining AND it’s 8am, then let’s go for a walk else let’s stay home.

  • Both conditions must be true to go for a walk.
  • If either condition is false, they will stay home.
  • AND statements must have all conditions true to work.

4 of 12

Using OR

  • Scenario #2

If the sun is shining OR it is 8am, then let’s go for a walk, else let’s stay home.

  • Only one of the operands must be true in order to go for a walk.
  • Both operands must be false in order to stay home.
  • OR statements must have at least one condition true to work.

5 of 12

Using NOT

  • Scenario #3

If NOT the sun is shining, then let’s go for a walk �else let’s stay home.

  • NOT operators in Java are always placed before the variable.
  • If the sun is not shining, they will go for a walk.

6 of 12

Truth Tables

  • A truth table shows how the value of the overall condition depends on the values of the operands.��Let’s look at an example...

7 of 12

Truth Tables

  • Back to Scenario #1�

If the sun is shining AND it is 8am, then let’s go for a walk else let’s stay home.

Sun Shining

8am

Sun Shining & 8am

Action �Taken

True

True

True

Walk

True

False

False

Stay Home

False

True

False

Stay Home

False

False

False

Stay Home

8 of 12

Truth Tables

  • Create a truth tables for scenarios #2 and #3.

9 of 12

Writing this in Java Code

  • AND &&
    • if (x > 10 && x < 15)

  • OR ||
    • if (x > 10 || x = 1)

  • NOT !
    • if ( ! (3 <= x) )

10 of 12

Java Logical Operators and Precedence

  • Like mathematical operations, logical operators are performed in a certain order. Some take precedence over others…

          • NOT !
          • Multiplication *
          • Division /
          • Addition +
          • Subtraction -
          • Relational Operators > >= < <=
          • AND &&
          • OR ||

11 of 12

Short-Circuit Evaluation

  • Sometimes the JVM knows that entire value of the condition before it’s even finished…

  • Example:
    • if (x > 2 && x < 6)
    • The JVM finds out that x is not greater than 2, so it does not continue on to calculate the next relational statement.
    • This is called short-circuit evaluation.

12 of 12

Short Circuit Evaluation

  • The JVM is efficient and does not waste time evaluating unnecessary statements.
  • Not all programming languages do this. These languages use complete evaluation instead. They perform all calculations instead.