This chapter goes into more depth about relational and logical operators. You will have to use these concepts to write complex programs that other people can read and follow.
2. Boolean Data and Operators
2.3. Short-Circuit Evaluation
Another important feature of the boolean operators is that they utilize a form of evaluation known as short-circuit evaluation. In short-circuit evaluation, a boolean expression is evaluated from left to right, and the evaluation is discontinued as soon as the expression's value can be determined, regardless of whether it contains additional operators and operands. For example, in the expression
expr1 && expr2 |
---|
expr1 || expr2 |
---|
In addition to being a more efficient form of evaluating boolean expressions, short-circuit evaluation has some practical uses. For example, we can use short-circuit evaluation to guard against null pointer exceptions. Recall from Chapter 2 that a null pointer exception results when you try to use an uninstantiated reference variable - that is, a reference variable that has not been assigned an object. For example, if we declare a OneRowNim variable without instantiating it and then try to use it, a null pointer exception will result:
OneRowNim game; |
// Uninstantiated Reference |
if (! game .gameOver ( )) |
// Null pointer exception |
game. takeSticks (num); |
In this code, a null pointer exception results when we use game in the method call game.gameOver(). We can use short-circuit evaluation to prevent the exception from occurring:
if (( game !=
null ) && ( !
game .gameOver()))
|
---|