Why this boolean statement is true?
a= 10;
b = 0;
7 < a || a == b && b > 9 - a / b
Since anything divided by 0 is error
Why this boolean statement is true?
a= 10;
b = 0;
7 < a || a == b && b > 9 - a / b
Since anything divided by 0 is error
Since the first operand of the OR (||
) operator (a > 7) evaluates to true
, it short circuits and nothing else is evaluated. Therefore the entire expression evaluates to true
.
7 < a
returns true. Since it's a ||
after, the rest isn't executed.
This is because true || false
is true, and true || true
is true too, so evaluing the second member is but a waste of time.
Your OR-Operator ||
uses lazy evaluation or short-circuit evaluation. This means, since the very first expression 7 < a
is true, it won't evaluate any other statements including the one with a division by zero, since java already found something true.
If you actually want to get an error, you can use this OR-Operator |
which should enforce the evaluation of all statements. Most only use it as a bitwise-operator, but its also a non-short-circuit version of ||
. For a more in-depth look at ||
vs. |
, look here.
For example,
boolean c = (7 < a | a == b && b > 9 - a / b);
will cause an ArithmeticExcption, as expected.