Friday, 10 July 2009

Boolean Logical Operators

Boolean Logical Operators
These operators operate on boolean operands and result
is also boolean. Like relational and equality, they are also
used frequently in if blocks and different loop for decision
making.
Operator Description
& Logical AND : evaluates to true if both operands evaluate to true
Logical OR : evaluates to true if both operands evaluate to true
^ Logical XOR : evaluates to true if odd no of operands are true
Short circuit OR
&& Short circuit AND
! Unary NOT
?: Ternary

Difference between & and &&

& : It evaluates both the operands
&& : It won't evaluate the second operand if the first operand evaluates to false
Example
Case 1
boolean flag = false ;
int count = 5 ;
if (flag & count ++ < 6)
{
// something
}
System.out.println (i) ; // count is 6 here

Case 2
boolean flag = false ;
int count = 5 ;
if (flag && count ++ < 6)
{
// something
}
System.out.println (i) ; // count is 5 here
In the second case, short circuit AND is used.When flag
evaluates to false, it does not go to the second part of
expression. Hence count ++ is not executed
Difference between and
: It evaluates both the operands
: It won't evaluate the second operand if the first operand evaluates to true
You can work it out on the lines of above example

Unary NOT
  • It simply returns toggled value of it's operand.
  • Operand remains unaffected.
    boolean flag = false ;
    if (! flag)
    {
    System.out.println ("flag still false " + flag) ;
    }
    Here, if block would be executed as NOT operator returns true but
    flag still holds false

    Ternary operator
    General syntax is
    exp ? statement 1 : statement 2
    exp: expression evaluating to a boolean
    If exp evaluates to true statement 1 is executed
    otherwise statement 2
    It can be thought of of as a shorthand for if else block