Java Data and Operators

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

if expr1 is false, then the AND expression must be false, so expr2 need not evaluated. Similarly, in the expression

expr1 || expr2

if expr1 is true, then the OR expression must be true, so expr2 need not evaluated.


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()))
game.takeSticks (num );

In this case, because game != null is false, neither method call involving game is made, thus avoiding the exception.