Short circuit and Bitwise AND and OR operators

We can use logical operators AND (&&) and OR (||) in the logical expressions. The AND operator returns true if both conditions are true while OR returns true if only one of the conditions is true. 

 

Short circuit operators

  1. The logical operators && and || are called short circuit operators.

  2. Short circuiting is the process of stop evaluating remainder of a logical expression once the result becomes obvious.

  3. Case 1: if(cond1 && cond2)

    1. If the first condition is false, the result will be always false irrespective of the rest of the expression; hence second condition won’t be evaluated.

  4. Case 2: if(cond1 !! cond2)

    1. If the first condition is true, the result will be always true irrespective of the rest of the expression; hence second condition won’t be evaluated.

 

Bitwise AND (&) and OR (|) operators

  1. If we don’t want short circuiting for any reason, we can use the bitwise AND (&) and OR (|) operators instead of logical AND (&&) and OR (||) operators.

  2. These bitwise operators perform the && or || operations bit-by-bit for each bit of the operand.

  3. As the internal representation of true and false use a single bit, the result of using bitwise operators will be the same as the corresponding logical operators, but there won’t be any short circuiting and both conditions will always be evaluated.

 

Example: Without and with short circuiting

Execute the below program or predict the output:

public class ShortCircuitTest {

    public static void main(String[] args) {

        myMethod(null);

    }
    
    static void myMethod(Object o) {
        if (o != null & o.equals(o)) {
            System.out.println(true);
        } else {
            System.out.println(false);
        }
    }

}

If you run this program you will get the exception as:

Exception in thread "main" java.lang.NullPointerException
    at ShortCircuitTest.myMethod(ShortCircuitTest.java:10)
    at ShortCircuitTest.main(ShortCircuitTest.java:5)

 

However if you change the operator '&' with '&&',

  • Java will see that since the first condition of 'o!=null' is not true,

    • there is no way the final output will be true irrespective of the result of the second condition 'o.equals(o)',

      • as AND need both conditions to be true.

  • Hence, Java will not evaluate the second condition and there will not be any NullPointerException. The program will print false.

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!