Cookie Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

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

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

Cookie Program

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 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.

// Cookie Ingredients Checker
//
import java.util.Scanner;
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...." );
  }
}

Try the program with various values of flour and sugar to check that you understand how AND works.

QUESTION 6:

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