& 和有什么不一样和&&在爪哇? [英] What is the difference between & and && in 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) 评估为假整个事情直接评估为假而不评估 (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 ||
.
这篇关于& 和有什么不一样和&&在爪哇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!