Logical Operators


Suppose you want to execute a line of code only if two separate conditions both hold true. You can use cascading if statements to guard that line of code:

 if (isFullTime)    if (isInState)       rate *= 0.9; 

Using logical operators, you can combine multiple conditionals into a single complex boolean expression:

 if (isFullTime && isInState)    rate *= 0.9; 

The double ampersands symbol (&&) is the logical and operator. It is a binary operatorit separates two boolean expressionsthe operands. If the result of both operands is TRue, the result of the entire conditional is TRue. In any other case, the result of the entire conditional is false. Here is the test-driven truth table (TDTT[1]) that represents the possible combinations of the logical and operator:

[1] A fabricated but cute acronym.

 assertTrue(true && true); assertFalse(true && false); assertFalse(false && true); assertFalse(false && false); 

The logical or operator (||), also a binary operator, returns true if either one of the two operands returns true or if both operands return true. The logical or operator returns false only if both operands are false. The TDTT for logical or:

 assertTrue(true || true); assertTrue(true || false); assertTrue(false || true); assertFalse(false || false); 

The logical not operator (!) is a unary operator that reverse the boolean value of an expression. If the source expression is true, the not operator results in the entire expression returning false, and vice versa. The TDTT:

 assertFalse(!true); assertTrue(!false); 

The logical exclusive-or (xor) operator (^) is a less frequently used binary operator that returns false if both operands result in the same boolean value. The TDTT:

 assertFalse(true ^ true); assertTrue(true ^ false); assertTrue(false ^ true); assertFalse(false ^ false); 

You can combine multiple logical operators. If you do not provide parentheses, the order of precedence is !, then &&, then ^^, then ||.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net