简体   繁体   中英

SOS for Java boolean statement

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 true || false is true, and true || true 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM