& 和有什么区别和&&在 Java 中?

2022-01-19 00:00:00 operators bitwise-operators boolean java

我一直以为Java中的&&操作符是用来验证它的布尔操作数是否为true& 运算符用于对两种整数类型进行按位运算.

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & operator is used to do Bit-wise operations on two integer types.

最近我知道&操作符也可以用来验证它的两个布尔操作数是否为true,唯一的区别是它甚至会检查RHS操作数如果 LHS 操作数为假.

Recently I came to know that & operator can also be used verify whether both its boolean operands are true, the only difference being that it checks the RHS operand even if the LHS operand is false.

Java 中的 & 运算符是否在内部重载?或者这背后是否有其他概念?

Is the & operator in Java internally overloaded? Or is there some other concept behind this?

推荐答案

&<-- 验证两个操作数
&&<-- 如果第一个操作数的计算结果为假,则停止计算,因为结果将为假

& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) &(1/x > 1) <-- 这意味着评估 (x != 0) 然后评估 (1/x > 1) 然后做 &.问题是对于 x=0 这将引发异常.

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) &&(1/x > 1) <-- 这意味着评估 (x != 0) 并且只有当这是真的时才评估 (1/x > 1) 所以如果你有 x=0 那么这是完全安全的,并且如果 (x != 0) 评估为 false 整个事情直接评估为 false 而不评估 (1/x > 1).

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

exprA |exprB <-- 这意味着先评估 exprA 然后评估 exprB 然后执行 |.

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA ||exprB <-- 这意味着评估 exprA 并且只有当这是 false 时才评估 exprB 并执行 ||.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

相关文章