Boolean Expressions

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Boolean Expressions
Printed by: Guest user
Date: Thursday, July 7, 2022, 11:49 AM

Description

This chapter introduces relational and logical operators. It also discusses the use of these operators to write Boolean expressions.

1. Boolean Expressions

The if statements of the previous chapters asked simple true/false questions (boolean expressions) such as count<10. Often simple boolean expressions are not enough. This chapter discusses more complicated boolean expressions.

Boolean expressions have been prominent on past AP Computer Science tests.

Chapter Topics:

      • Relational Operators (review)
      • Logical Operators
      • AND Operator
      • How to check that a number is in range
      • Boolean Expressions
      • OR Operator
      • Comparison between AND and OR
      • NOT Operator

Question 1:

You have decided to bake some cookies (much cheaper than buying them at the Mall).

An interesting cookie recipe calls for 4 cups of flour and 2 cups of sugar. You look in your pantry and
find 3 cups of flour and 2 cups of sugar.

Can you bake cookies with what you have?


Source: Bradley Kjell, http://programmedlessons.org/Java9/chap18/ch18_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.

2. Both Items Needed


Answer:

No. You have enough sugar, but not enough flour, so you can't follow the recipe.

Both Items Needed

The question about whether you have enough ingredients has two parts:

You need at least 4 cups of flour    AND    You need at least 2 cups of sugar

Since you do not have enough flour, you don't have enough ingredients. (:<)


Question 2:

What if you had 9 cups of flour and 1 cup of sugar. Now could you follow the recipe?

3. Cookie Calculator


Answer:

No. You need 4 cups of flour and 2 cups of sugar. Now you have more than enough flour,
but not enough sugar, so you can't follow the recipe.

Cookie Calculator

In order to bake cookies two things must both be true:

      • You must have 4 or more cups of flour.
      • You must have 2 or more cups of sugar.

If just one of these is false, then you do not have enough ingredients. Here is a simulation of the cookie program. Enter some values for sugar and flour and see if you can bake cookies. Use only integers as input.

How much flour do you have? 
How much sugar do you have?  if ( flour >= 4 && sugar >= 2 ) System.out.println( "Enough for cookies!" ); else System.out.println( "sorry...." );   

The symbol && means AND. The if statement asks a question with two parts:

if ( flour >= 4 && sugar >= 2 )
---------- ----------
flour part sugar part

Each part is a relational expression. A relational expression is a type of boolean expression that uses a relational operator to compute a true or false value.

The entire expression between parentheses is also a boolean expression. A boolean expression is often composed of smaller boolean expressions. This is similar to human language where compound sentences are made from smaller sentences.


Question 3:

Say that you enter 9 for flour and 1 for sugar. What value (true or false) does each part give you?

    flour >= 4
    sugar >= 2

4. &&


Answer:

flour >= 4  true

sugar >= 2  false 

&&

Examine this part of the program:

// check that there is enough of both ingredients
if ( flour >= 4 && sugar >= 2 )
System.out.println("Enough for cookies!" );
else
System.out.println("sorry...." );

For you to have enough ingredients, both relational expressions must be true. This is the role of the && (and-operator) between the two relational expressions. The && requires that both

flour >= 4 

and

sugar >= 2 

are true for the entire expression to be true. The entire question must be true in order for the true branch to execute.

The and operator && is a logical operator. A logical operator examines two true/false values and outputs a single true/false value.


Question 4:

What is printed if the user enters 6 for flour and 4 for sugar?

5. AND Operator


Answer:

    How much flour do you have? 6 How much sugar do you have? 4 Enough for cookies!

When execution gets to the if statement, it finds that

    flour >= 4
is true, because 6 >= 4. And
    sugar >= 2
is true, because 4 >= 2 Both sides are true, so AND gives true.

AND Operator

andOperator

The and operator requires that both sides are true:

this side must be true && this side must be true

If both sides are true, the entire expression is true. If either side (or both) are false, the entire expression is false. && is a logical operator because it combines two true/false values into a single true/false value.

Here is what && does:

      • true  && true  = true
      • false && true  = false
      • true  && false = false
      • false && false = false

Use and when every requirement must be met.


Question 5:

Look at the boolean expression:

    flour >= 4 && sugar >= 2
What will the expression give us if flour is 2 and sugar is 0?

6. Short-circuit Evaluation


Answer:

The whole expression will be false, because && combines two falses into false.

flour >= 4 && sugar >= 2
 ---------     --------
   false   &&    false
      ---------------
          false 

Short-circuit Evaluation

In fact, as soon as the first false is detected, you know that the entire expression must be false, because false AND anything is false.

flour >= 4 && sugar >= 2
--------- ------------
false && does not matter
---------------
false

As an optimization, Java only evaluates an expression as far as needed to determine the value of the entire expression. When the program runs, as soon as flour >= 4 is found to be false, the entire expression is known to be false, and the false branch of the if statement is taken. This type of optimization is called short-circuit evaluation. (See the chapter on this topic.)

Here is a full Java version of the cookie program. Compile and run the program with various values of flour and sugar to check that you understand how AND works.


// Cookie Ingredients Checker
//
import java.util.Scanner;
public class CookieChecker
{
public static void main (String[] args)
{
// Declare a Scanner and two integer variables
Scanner scan = new Scanner( System.in );
int sugar, flour; // get the number of cups of flour
System.out.println("How much flour do you have?");
flour = scan.nextInt(); // get the number of cups of sugar
System.out.println("How much sugar do you have?");
sugar = scan.nextInt(); // check that there are enough of both ingredients

if ( flour >= 4 && sugar >= 2 )
System.out.println("Enough for cookies!" );
else
System.out.println("sorry...." );
}
}


Question 6:

Try the program with exactly enough flour and sugar. Can you bake cookies?

7. Car Rental Problem


Answer:

Yes. It is always good to test programs with values that are right at the limit.

Car Rental Problem

A car rental agency wants a program to determine who can rent a car. The rules are:

      • A renter must be 21 years old or older.
      • A renter must have a credit card with $10,000 or more of credit.

The program looks something like the cookie program:


// Rental Car Checker
//
import java.util.Scanner;
public class RenterChecker
{
public static void main (String[] args)
{
// Declare a Scanner and two integer variables
Scanner scan = new Scanner( System.in );
int age, credit; // get the age of the renter
System.out.println("How old are you?");
age = scan.nextInt() ; // get the credit line
System.out.println("How much credit do you have?");
credit = scan.nextInt() ; // check that both qualifications are met

if ( && )
System.out.println("Enough to rent this car!" );
else
System.out.println("Have you considered a bicycle?" );
}
}


Question 7:

Complete the program by filling in the blanks.

Consider carefully what relational operators to use.

8. More Renters


Answer:

    if ( age>=21 && credit>=10000 )

The relational operators are both >= because the renter may be exactly 21 and may have exactly $10,000 credit.
Using > where greater-or-equal is required is a common mistake.

The customer must get true for both the age test and the credit test. If both tests are passed, the && combines
the two true's into true.

More Renters

A 24 year old customer with $0 credit could not rent a car. The boolean expression looks like this:

age >= 21 && credit >= 10000
--------- ---------------
true false
----------------
false

A 19 year old customer with $500000 credit could not rent a car. The boolean expression looks like this:

age >= 21 && credit >= 10000
--------- ---------------
false true
----------------
false


Question 8:

Could a 30 year old with $10000 credit rent a car?

9. Range Testing


Answer:

A 30 year old with $10000 credit could rent a car.
    age >= 21 && credit >= 10000 --------- --------------- true true ---------------- true

Range Testing

Frequently you need to test if a number is within a certain range.

A welter weight boxer must weight between 136 and 147 pounds. A boxer's weight is tested before each fight to be sure that he is within his weight category. Here is a program that checks if a welter weight boxer's weight is within range:

// Ringside Weigh-in
//
// Boxer must weigh between 136 and 147 pounds
//
import java.util.Scanner; public class Ringside
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int weight; // get the weight
System.out.print("How heavy is the boxer? ");
weight = scan.nextInt(); // check that the weight is within range
if ( )
System.out.println("In range!" );
else
System.out.println("Out of range." );
}
}

Question 9:

Fill the blank so that weight is tested in two ways:

    1. weight must be equal or greater than 136
    2. weight must be less than or equal to 147

10. A Common Mistake


Answer:

  // check that the weight is within range
    if ( weight >= 136 && weight <= 147 )
      System.out.println("In range!" );
    else
      System.out.println("Out of range." );

Another correct answer is:

    // check that the weight is within range
    if ( 136 <= weight && weight <= 147 )
      System.out.println("In range!" );
    else
      System.out.println("Out of range." );

Here is another correct (but unclear) answer:

    // check that the weight is within range
    if ( weight < 148 &&  135 < weight )
      System.out.println("In range!" );
    else
      System.out.println("Out of range." );

There are more than a dozen correct answers. But the best answers are both correct and clear.

A Common Mistake

The boxer must weigh enough (weight >= 136), and must also not weigh too much (weight <= 147). The results of the two tests are combined with the and-operator, &&.

A common mistake is to fail to use two separate comparisons. The following does not work:

if ( 136 <= weight <= 147 )  // wrong

The above is incorrect because 136 <= weight forms a boolean subexpression. The second <= would try to compare a boolean to an integer.

136 <= weight <= 147
-------------- ---
boolean <= 147

Here is a JavaScript version of the program:

if ( weight >= 136 && weight <= 147 )
System.out.println("In Range")
else
System.out.println("Out of Range")
How heavy is the boxer? 

Question 10:

Try the program with the weight 140.

11. Tax Bracket


Answer:

    How heavy is the boxer? 140 In range!

The AND operator gives true because both sides are true:

    weight >= 136 && weight <= 147 140 >= 136 && 140 <= 147 ------------ ----------- true true ----------------- true

Tax Bracket

An unmarried taxpayer in the US with an income of $24,000 up to $58,150 (inclusive) falls into the 28% "tax bracket." Here is a program that tests if a taxpayer falls into this bracket.

// IRS Weigh-in
//
// Income between $24000 and $58150 inclusive // import java.util.Scanner; public class TaxGouge { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int income; // get the income System.out.println("What is your income?"); income = scan.nextInt(); // check that the income is within range for the 28% bracket if (
 )
      System.out.println("In the 28% bracket." );
    else
      System.out.println("Time for a tax audit!" );
  }
}       

Question 11:

Fill in the blank to test if the income is within this tax bracket.

12. Complete Boolean Expressions


Answer:

// check that the income is within range for the 28% bracket
if ( income >=24000 && income <= 58150  )
  System.out.println("In the 28% bracket." );
else
  System.out.println("Time for an audit!" );

Complete Boolean Expressions

AND combines the results of two boolean values. In this example, the boolean values are produced by relational expressions, like this:

income >= 24000  &&  income <= 58150
------------- ---------------
relational relational
expression expression

Each relational expression must be complete. The following is a MISTAKE:

income >= 24000  &&      <= 58150
------------- ---------------
relational not a complete
expression relational
expression

This is INCORRECT because the characters that follow && do not form a complete relational expression. The Java compiler would not accept this.


Question 12:

Here is an incorrect boolean expression that is intended to test if a person's age is between 21 and 35.

    age >= 21 && <= 35
Fix the boolean expression.

13. Either Order (usually)


Answer:

    age >= 21 && age <= 35

Either Order (usually)

In most situations, the operands of AND can be in either order. The following

age >= 21 && age <= 35 

is the equivalent of this:

age <= 35 && age >= 21 

One false is enough to make the entire expression false, regardless of where the false occurs.

Warning: If a boolean expression includes an assignment operator or method calls, then the order sometimes does matter. The reason for this involves the short-circuit optimization mentioned previously. Mostly you don't need to worry about this, but make a mental note about this potential problem.

One of the next chapters describes this situation in detail. For the examples in this chapter, the order of operands does not matter.


Question 13:

Examine this expression:

    ( Monster.isAlive() && (hitpoints = Hero.attack()) < 50 )

Do you suspect that the order of operands in this expression matters?

14. Buying a Car with Cash


Answer:

Yes, since the expression involves calling two methods and also uses an assignment operator.

    Buying a Car with Cash

    You would like to buy a $25,000 red Miata sports car. To pay for the car you need either enough cash or enough credit.

    Let us ignore the possibility of combining cash and credit.

    redMiata



    Question 14:

    You found $34,951 in your cookie jar. Can you buy the $25,000 Miata?

    15. Buying on Credit

    
    

    Answer:

    Yes. You have enough money for the car. But what happened to the cookies?

    Buying on Credit

    Recall the problem:

    You would like to buy a new $25,000 red Miata sports car. To buy the car, you could pay cash for it, or you could buy it on credit.

    You might not have $25,000 on hand. The cookie jar seems to be empty. No problem — you can buy on credit, if you qualify.


    Question 15:

    You have $240 on hand. The credit manager is willing to extend you up to $30,000 of credit.
    Can you buy the $25,000 Miata?

    16. Student Car Purchase

    
    

    Answer:

    Yes. You have enough credit for the car.

    Student Car Purchase

    Recall the problem:

    You would like to buy a new $25,000 red Miata sports car. You can pay in cash, or you can buy it on credit.

    It turns out that you actually have $240 on hand and are an unemployed student majoring in philosophy. The credit manager is unwilling to extend any credit to you.


    Question 16:

    You have $240 on hand and no credit. Can you buy the $25,000 Miata?

    17. Car Purchase Decision

    
    

    Answer:

    No

    Car Purchase Decision

    You need money OR credit. Just one would be enough. Of course, if you had lots of money and plenty of credit you could certainly buy the car.

    Sometimes a program has to test if one or the other (or both) of the conditions has been met. Here is how that is done with the car purchase problem.


    How much cash do you have?    
    
    How much credit do you have?  
    
      if ( cash>=25000 ||  credit>=25000 )
        System.out.println("Enough to buy this car!");
      else
        System.out.println("Have you considered a Yugo?");
    
    
      
           

    The symbol || (vertical-bar vertical-bar) means OR. On your keyboard, vertical-bar is the top character on the key above the "enter" key. The OR operator evaluates to true when either qualification is met or when both are met. The if statement asks a question with two parts:

    if ( cash >= 25000 ||  credit >= 25000  )
    ------------- -------------
    cash part credit part

    If either part is true, or both parts are true, then the entire boolean expression is true.


    Question 17:

    Say that you enter 56000 for cash and 0 for credit. What answer (true or false) does each part give you?

      cash >= 25000 credit >= 25000

    What does the entire boolean expression give you?

      cash >= 25000 || credit >= 25000

    18. Boolean Expressions with OR

    
    

    Answer:

      cash >= 25000 true credit >= 25000 false cash >= 25000 || credit >= 25000 true

    Boolean Expressions with OR

    orOperator

    The OR operator is used in a boolean expression to check that there is at least one true. If both sides are true, the entire expression is true. If just one side is true, the entire expression is true. If both sides are false, the entire expression is false. The OR operator is a logical operator because it combines two true/false values into a single true/false value.

    Here is how || works:

        • true  || true  = true
        • false || true  = true
        • true  || false = true
        • false || false = false

    OR checks that at least one requirement is met. This type of OR is called an inclusive OR because its value is true for one or two true values.

    Often in English word "or" is used when any number of conditions can be true. For example, in this sentence

    Successful job seekers must have experience or training.

    Sometimes the English word "or" is used when only one condition can be true at a time. For example, in this sentence

    It will rain today or it will be clear.

    only one condition, "rain" or "clear", can be true. This is called an exclusive OR. In programming, "or" means inclusive or.


    Question 18:

    Here is a boolean expression:

      34 > 2 || 5 == 7
    Is this expression true or false ?

    19. Car Purchase Program

    
    

    Answer:

    The boolean expression is true
      34 > 2 || 5 == 7
      ------ -----
      true false
      --------------
      true
      because all OR needs is one true.

      Car Purchase Program

      The above expression evaluates to true because at least one operand was true. In fact, as soon as the first true is detected, you know that the entire expression must be true, because true OR anything is true.

      34 > 2   ||   5 == 7
      ------ -----
      true does not matter
      --------------
      true

      As an optimization, Java evaluates an expression only as far as needed to determine its value. When program runs, as soon as 34 > 2 is found to be true, the entire expression is known to be true, and evaluation goes no further. This type of optimization is called short-circuit evaluation. (Just as it is with AND.)

      Here is a full Java program that implements the car purchase decision.

      // Sports Car Purchase
      //
      // You need $25000 in cash or credit
      //
      import java.util.Scanner;
      
      public class HotWheels
      {
        public static void main (String[] args) 
        { 
          Scanner scan = new Scanner( System.in ); 
          int cash, credit ; 
      
          // get the cash
          System.out.print("How much cash? ");
          cash = scan.nextInt() ; 
      
          // get the credit line
          System.out.print("How much credit? ");
          credit = scan.nextInt() ; 
      
          // check that at least one qualification is met
          if ( cash >= 25000  ||   credit >= 25000 )
            System.out.println("Enough to buy this car!" );
          else
            System.out.println("What about a Yugo?" );
      
        }
      }

      Compile and run the program with various values of cash and credit to check that you understand how OR works.

      Question 19:

      What does the program do if the user enters negative numbers?

      20. Insulated Wall Problem

      
      

      Answer:

      The program runs. However, it is not clear what negative values mean in this situation. The program could be improved by
      calling the user's attention to possibly erroneous data.

      Insulated Wall Problem

      To meet building code requirements, outside walls of new houses must be well insulated. Say that the building code requires outside walls to be insulated with at least 4 inches of fiberglass batting or with at least 3 inches of foam insulation.

      Here is a program that asks for the number of inches of fiberglass and the number of inches of foam and determines if a new house meets the building code.

      import java.util.Scanner;
      public class HotHouse
      {
        public static void main (String[] args) 
        { 
          Scanner scan = new Scanner( System.in ); 
          int fiber, foam ; 
      
          // get the inches of fiber
          System.out.println("How much fiber?");
          fiber = scan.nextInt() ;  
      
          // get the inches of foam
          System.out.println("How much foam?");
          foam  = scan.nextInt() ;  
      
          // check that at least one requirement is met
          if (  ||  )
            System.out.println("House passes the code requirements!" );
          else
            System.out.println("House fails." );
      
        }
      }


      Question 20:

      Fill in the blanks so that the program works correctly.

      21. NOT!

      
      

      Answer:

      5 > 2 || 12 <= 7
          T  
      5 > 2 && 12 <= 7
          F  
      3 == 8 || 6 != 6
          F  
      3 == 8 && 6 != 6
          F  

      NOT!

      A
      !A
      true
      false
      false
      true

      The NOT operator in Java is this:   !   (exclamation point). The NOT operator changes true to false and false to true, as seen in the truth table. This may seem like a silly thing to do, but often it is useful. Sometimes it is more natural to express a condition in a particular way, but the program logic calls for the reverse of what you have written. Time for the NOT operator.

      Say that you are shopping for new shoes. You are only interested in shoes that cost less than $50. Here is a program fragment:

      if (  ______(cost < 50)  )
      System.out.println("Reject these shoes");
      else
      System.out.println("Acceptable shoes");

      Question 22:

      Fill in the blank so that the program fragment rejects shoes that do not cost less than $50.

      22. Example

      
      

      Answer:

        if ( !(cost < 50) ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes");

      (There are other ways to write this fragment. See below.)

      Example

      It is important to put parentheses around the entire expression so the NOT is applied correctly. Say that you are considering a pair of $35 shoes. Evaluation proceeds like this:

      ! ( cost < 50 )

      ! ( 35 < 50 )
      -----+----
      |
      ! ( T )
      ------+--------
      |
      F

      The entire condition evaluates to false and so the false branch of the if statement is selected. The program prints out "Acceptable shoes".


      Question 23:

      Is the following program fragment correct?

        if ( !cost < 50 ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes");

      23. Precedence of NOT

      
      

      Answer:

      No. In this defective fragment, the NOT (the !) applies directly to cost.

      Precedence of NOT

      The NOT operator has high precedence, so it is done before arithmetic and relational operators unless you use parentheses. Examine the following:

      !cost < 50 
      -----
      illegal: can't use ! on an arithmetic variable

      Since ! has high precedence, the above says to apply it to cost. This which won't work, because cost is an integer and NOT applies only to boolean values.


      Question 24:

      You need new shoes. But all you can afford is a pair of shoes that costs less than fifty dollars.

      Look at these fragments of code. Does each do the same thing?


        if ( cost < 50 ) System.out.println("Acceptable shoes"); else System.out.println("Reject these shoes");

        if ( !(cost < 50) ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes");

        if ( cost >= 50 ) System.out.println("Reject these shoes"); else System.out.println("Acceptable shoes");

        if ( !(cost >= 50) ) System.out.println("Acceptable shoes"); else System.out.println("Reject these shoes");

      Mentally try a few costs with each fragment to see if they are equivalent.

      24. End of Chapter

      
      

      Answer:

      Yes. The fragments are equivalent, although the first fragment is easiest to read.

      End of Chapter

      You have reached the end of this chapter. If (you are a good student) or (you are interested) you may wish to review the following.