Which set is short-circuiting, and what exactly does it mean that the complex conditional expression is short-circuiting?
public static void main(String[] args) {
int x, y, z;
x = 10;
y = 20;
z = 30;
// T T
// T F
// F T
// F F
//SET A
boolean a = (x < z) && (x == x);
boolean b = (x < z) && (x == z);
boolean c = (x == z) && (x < z);
boolean d = (x == z) && (x > z);
//SET B
boolean aa = (x < z) & (x == x);
boolean bb = (x < z) & (x == z);
boolean cc = (x == z) & (x < z);
boolean dd = (x == z) & (x > z);
}
SET A uses short-circuiting boolean operators.
What 'short-circuiting' means in the context of boolean operators is that for a set of booleans b1, b2, ..., bn, the short circuit versions will cease evaluation as soon as the first of these booleans is true (||) or false (&&).
For example:
In plain terms, short-circuiting means stopping evaluation once you know that the answer can no longer change. For example, if you are evaluating a chain of logical
AND
s and you discover aFALSE
in the middle of that chain, you know the result is going to be false, no matter what are the values of the rest of the expressions in the chain. Same goes for a chain ofOR
s: once you discover aTRUE
, you know the answer right away, and so you can skip evaluating the rest of the expressions.You indicate to Java that you want short-circuiting by using
&&
instead of&
and||
instead of|
. The first set in your post is short-circuiting.Note that this is more than an attempt at saving a few CPU cycles: in expressions like this
short-circuiting means a difference between correct operation and a crash (in the case where mystring is null).
The
&&
and||
operators "short-circuit", meaning they don't evaluate the right hand side if it isn't necessary.The
&
and|
operators, when used as logical operators, always evaluate both sides.There is only one case of short-circuiting for each operator, and they are:
false && ...
- it is not necessary to know what the right hand side is, the result must befalse
true || ...
- it is not necessary to know what the right hand side is, the result must betrue
Let's compare the behaviour in a simple example:
The 2nd version uses the non-short-circuiting operator
&
and will throw aNullPointerException
ifinput
isnull
, but the 1st version will returnfalse
without an exception;