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
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.
|
Question 6:
Try the program with exactly enough flour and sugar. Can you bake cookies?