Menu
Topics Index
...
`


Operators >
Siva Nookala - 12 Apr 2016
Java provides two boolean operators boolean AND and boolean OR which are not provided by the other language and these operators are known as Short-Circuit logical operators. These operators gets the result of an logical operator, evaluating the right hand operator only if required.

As per the Boolean Logical Table for a logical AND (&) operation, if the left hand (first) operand is false, then the result is false irrespective of the right hand (second) operand. When short-circuit AND (&&) is used, if the first value is false, second value is not evaluated. Similarly for short-circuit OR (||), if the first value is true, then second value is not evaluated. These short-circuit operators will be useful when we want to control the evaluation of right hand operand.
if( denom !=0 && num / denom > 10 )
Here, the right hand expression num / denom > 10 will be evaluated only when denom is not zero, thus preventing divide by zero ArithmeticException.
Short circuit AND
class ShortCircuitAnd
{
    public static void main(String arg[])
    {
        int c = 0, d = 100, e = 50; // LINE A
        if( c == 1 && e++ < 100 )
        {
            d = 150;
        }
        System.out.println("e = " + e );
    
    }
}
OUTPUT

e = 50

DESCRIPTION

Since c is 0, which is not equal to one, the left hand operand is false and hence right hand operand is not evaluated and hence e is not incremented. But if c is set to 1, then left hand operand will be true and hence right hand operand will be evaluated, thus incrementing e, hence the output will be e = 51

THINGS TO TRY
  • Change the value of c to 1 in LINE A and see that the output will be e = 51
  • Change the value of c to 0 in LINE A and use logical AND (&) instead of short-circuit AND (&&) and see that the output will still be e = 51

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App