简体   繁体   English

SOS for Java布尔语句

[英]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 由于任何除以0的错误

Since the first operand of the OR ( || ) operator (a > 7) evaluates to true , it short circuits and nothing else is evaluated. 由于OR( || )运算符的第一个操作数(a> 7)评估为true ,因此它发生短路,并且没有其他评估。 Therefore the entire expression evaluates to true . 因此,整个表达式的计算结果为true

7 < a returns true. 7 < a返回true。 Since it's a || 由于是|| after, the rest isn't executed. 之后,其余的将不会执行。

This is because true || false 这是因为true || false true || false is true, and true || true true || false是true,而true || true true || true is true too, so evaluing the second member is but a waste of time. true || true也是如此,因此评估第二个成员只是浪费时间。

Your OR-Operator || 您的OR运算子|| 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. 这意味着,由于第一个表达式7 < a为真,因此它不会计算任何其他语句,包括除以零的语句,因为java已经找到了真值。

If you actually want to get an error, you can use this OR-Operator | 如果您确实想获取错误,则可以使用此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. 如预期的那样将导致ArithmeticExcption。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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