Java logical operator short-circuiting
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:
// 2 == 2 will never get evaluated because it is already clear from evaluating
// 1 != 1 that the result will be false.
(1 != 1) && (2 == 2)
// 2 != 2 will never get evaluated because it is already clear from evaluating
// 1 == 1 that the result will be true.
(1 == 1) || (2 != 2)
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 befalse
regardless of the value theretrue || ...
- it is not necessary to know what the right-hand side is because the result can only betrue
regardless of the value there
Let's compare the behaviour in a simple example:
public boolean longerThan(String input, int length) {
return input != null && input.length() > length;
}
public boolean longerThan(String input, int length) {
return input != null & input.length() > length;
}
The 2nd version uses the non-short-circuiting operator &
and will throw a NullPointerException
if input
is null
, but the 1st version will return false
without an exception.