#8 Logical operators in JAVA

Logical Operators


These operators are used to evaluate an expression and depending on the operator used, a particular output is obtained. In this case the operands must be Boolean data types and the result is also Boolean. The following table shows the available logical operators:


Operator         Description
&               AND Gate behaviour(0 0 0 1)
| OR Gate behaviour(0 1 1 1)
^ XOR-Exclusive OR(0 1 1 0 0)
&&             short-circuit AND
||                 short-circuit OR
!                 NOT


class Example5


{
 public static void main(String args[])
 {
int n, d;
n = 10; d = 2;
 if(d != 0 && (n % d) == 0)
System.out.println(d + " is a factor of " + n);
 d = 0;    // now, set d to zero // Since d is zero, the second operand is not evaluated.
if(d != 0 && (n % d) == 0)
System.out.println(d + " is a factor of " + n);   /* Now, try same thing without short-circuit operator. This will cause a divide-by-zero error. */
if(d != 0 & (n % d) == 0) System.out.println(d + " is a factor of " + n);

}
}

Predicted Output:
 *Note if you try to execute the above program you will get an error (division by zero). To be able to    execute it, first comment the last two statements, compile and then execute.
 2 is a factor of 10

Trying to understand the above program is a bit difficult, however the program highlights the main difference in operation between a normal AND (&) and the short-circuit version (&&). In a normal AND operation, both sides of the expression are evaluated, e.g.
if(d != 0 & (n % d) == 0) – this returns an error as first d is compared to 0 to check inequality and then the operation (n%d) is computed yielding an error! (divide by zero error)

The short circuit version is smarter since if the left hand side of the expression is false, this mean that the output has to be false whatever there is on the right hand side of the expression, therefore:

if(d != 0 && (n % d) == 0) – this does not return an error as the (n%d) is not computed since d is equal to 0, and so the operation (d!=0) returns false, causing the output to be false. Same applies for the short circuit version of the OR.


Comments

Popular Posts