EXPLORING TWO BOOLEAN OPERATORS
Two operators that are quite similar in functionality but for which a developer has to be conscious of bugs creeping into his code are the boolean logical inclusive or, | and conditional-or, ||, operators.
The operands for both operators should be of type boolean or the boolean wrapper, Boolean. One difference between both of them is that the conditional-or || operator evaluates its operands differently and in a subtle fashion than its counterpart, the boolean logical inclusive-or | operator.
Let's illustrate this with a truth table.
T | F | Result: Logical inclusive-or | operator | Result: conditional-or operator || |
T | T | T | T. Ignores right operand and proceeds to next expression. |
T | F | T | T. ignores right operand; proceeds to next expression |
F | T | T | T. evaluates right operand which is true where left operand if false and proceeds to next expression. |
F | F | F | F. evaluates right operand which is false where left operand is false. Proceeds to next expression. |
This is the difference between both operators: although they give the same result for truth or falsity, operand evaluation is different. From the table, realize that where the left operand is false for a conditional-or operand, the right operand is then evaluated, else where the left operand is true, the right operand is ignored.
So what's the consequence of this effect?
Let's take a simple question: which of the options below is not robust enough to throw a null pointer exception?
Option A: if ( (myArray != null) | (num == myArray.length()) );
Option B: if ( (myArray != null) || (num == myArray.length()) );
Option C: if ( (myArray == null) | (num == myArray.length()) );
Option D: if ( (myArray == null) || (num == myArray.length()) );
Answers:
Option A: if left operand is true and right operand is true or false, the if-statement evaluates to true and the expression after the if statement is next evaluated. If left operand is false, the if-statement will always throw a null pointer exception.
Option B: if left operand is true, execution jumps to the expression following the if statement, else a null pointer exception is immediately thrown.
Option C: if left operand is true, a null pointer exception is immediately thrown because the right operand would never be evaluated. If left operand is false, if statement evaluates to true if the right operand is true, false otherwise.
Option D: if left operand is true, execution immediately jumps to the statement following the if-statement. If left operand is false, right operand is then evaluated. If right operand is true or false, no null pointer exception will ever be executed.
So which option will never throw a null pointer? You guessed right, option D.
No comments:
Post a Comment