Boolean Expressions

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

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?