Engineering Full Stack Apps with Java and JavaScript
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.
The logical operators && and || are called short circuit operators.
Short circuiting is the process of stop evaluating remainder of a logical expression once the result becomes obvious.
Case 1: if(cond1 && cond2)
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.
Case 2: if(cond1 !! cond2)
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.
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.
These bitwise operators perform the && or || operations bit-by-bit for each bit of the operand.
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.
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.