按位运算符和布尔运算符 'AND' 之间的区别
正如标题所说,我需要知道 &
运算符和 &&
运算符之间的区别。 谁能用简单的话帮助我。
- 它们有何不同?
- IF 语句中应该使用哪一个?
Possible Duplicates:
logical operators in java
What's the difference between | and || in Java?
As the title says, I need to know the difference between &
operator and &&
operator.
Can anyone help me in simple words.
- How do they differ from each other?
- And which one to be used in a IF statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上存在三个“与”运算符:
a && b
,其中 a 和 b 为布尔值:评估 a。如果为真,则评估 b。如果为真,则结果为真。否则,结果为假。 不为 true,则不会评估 b。)a
b,其中 a 和 b 为布尔值:对两者求值,进行逻辑与(即仅当两者都为 true 时才为 true)。a& b
,其中 a 和 b 都是整型(int、long、short、char、byte):计算 a 和 b,并执行按位 AND。如果将
boolean
视为一位整数类型,则第二个可以视为第三个类型的特殊类型;-)作为
if
的顶级条件code>-语句您可以使用前两个,但第一个最有可能有用。 (也就是说,在很多情况下,您确实需要第二个,而第一个会做错事,但相反的情况更常见。在大多数情况下,第一个只是更快一点。)There are in fact three "and" operators:
a && b
, with a and b being boolean: evaluate a. If true, evaluate b. If true, result is true. Otherwise, result is false. (I.e. b is not evaluated ifa
is not true.)a & b
, with a and b being boolean: evaluate both, do logical and (i.e. true only if both are true).a & b
, where a and b are both integral types (int, long, short, char, byte): evaluate a and b, and do a bitwise AND.The second one can be viewed as a special type of the third one, if one sees
boolean
as a one-bit integral type ;-)As the top-level condition of an
if
-statement you can use the first two, but the first one is most likely useful. (I.e. there are not many cases where you really need the second and the first would do something wrong, but the other way around is more common. In most cases the first is simply a little bit faster.)如果第一个结果为 FALSE,
&&
不会计算第二个结果。&
确实如此。If the first result is FALSE,
&&
doesn't evaluate the second result.&
does.&&仅当第一个操作为 true 时才计算第二个表达式。 &计算两个表达式(即使第一个表达式为 false 并且计算第二个表达式没有意义)。因此&&比 & 快一点点在逻辑运算中。因此&&也称为短路和。
&除了逻辑运算符之外,还可以用作按位运算符。因此,您可以对 2 个数字进行“位与”,例如
&&不能用作位与运算符。
对于条件 IF 运算符,请使用 &&。它比 & 快一点点。
&& only evaluates the second expression if the first operation is true. & evaluates both expressions (even if the first expression is false and there is no point in evaluating the second expression). Hence && is a tiny bit faster than & in logical operations. Hence && is also known as short-circuit and.
& can also be used as a bitwise operator in addition to a logical operator. So you can do a 'Bit And' of 2 numbers like for example
&& cannot be used as a bit-and operator.
For conditional IF operator, use &&. It is a tiny bit faster than just &.