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);
}
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 because the result can only befalseregardless of the value theretrue || ...– it is not necessary to know what the right-hand side is because the result can only betrueregardless of the value thereLet’s compare the behaviour in a simple example:
The 2nd version uses the non-short-circuiting operator
&and will throw aNullPointerExceptionifinputisnull, but the 1st version will returnfalsewithout an exception.