As I was reading a colleague\'s Java code, I stumbled upon an army of if/else statements. In these statements, several &&
and ||
operators wer
It's simply because
if (false && true || true)
is equivalent to (&&
has a higher precedence)
if ((false && true) || true)
which is
if (false || true)
which is... true
.
Note: In the expression true || true && false
, the part true && false
is called a dead code because it doesn't affect the final result of the evaluation, since true || anything
is always true
.
It is worth mentioning that there exist &
and |
operators that can be applied to booleans, they are much like &&
and ||
except that they don't short circuit, meaning that if you have the following expression:
if (someMethod() & anotherMethod())
and someMethod
returns false
, anotherMethod
will still be reached! But the if
won't be executed because the final result will be evaluated to false
.