布尔运算符的区别: &与&&和|对|| [英] Differences in boolean operators: & vs && and | vs ||

查看:41
本文介绍了布尔运算符的区别: &与&&和|对||的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 &&|| 的规则,但什么是 &|?请用一个例子向我解释这些.

I know the rules for && and || but what are & and |? Please explain these to me with an example.

推荐答案

那些是按位 AND 和按位 OR 运算符.

Those are the bitwise AND and bitwise OR operators.

int a = 6; // 110
int b = 4; // 100

// Bitwise AND    

int c = a & b;
//   110
// & 100
// -----
//   100

// Bitwise OR

int d = a | b;
//   110
// | 100
// -----
//   110

System.out.println(c); // 4
System.out.println(d); // 6

感谢 Carlos 在 Java Language Spec (15.22.1, 15.22.2) 关于运算符基于其输入的不同行为.

Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.

实际上,当两个输入都是布尔值时,运算符被视为布尔逻辑运算符,其行为类似于条件与 (&&) 和条件或 (||) 运算符,但它们不会短路,因此以下是安全的:

Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&) and Conditional-Or (||) operators except for the fact that they don't short-circuit so while the following is safe:

if((a != null) && (a.something == 3)){
}

这不是:

if((a != null) & (a.something == 3)){
}

短路"意味着操作员不必检查所有条件.在上面的例子中,只有当 a 不是 null 时,&& 才会检查第二个条件(否则整个语句将返回 false,并且无论如何检查以下条件都没有实际意义),因此 a.something 的语句不会引发异常,或者被认为是安全的".

"Short-circuiting" means the operator does not necessarily examine all conditions. In the above examples, && will examine the second condition only when a is not null (otherwise the whole statement will return false, and it would be moot to examine following conditions anyway), so the statement of a.something will not raise an exception, or is considered "safe."

& 运算符总是检查子句中的每一个条件,所以在上面的例子中,a.something 可能在 a 时被评估实际上是一个 null 值,引发异常.

The & operator always examines every condition in the clause, so in the examples above, a.something may be evaluated when a is in fact a null value, raising an exception.

这篇关于布尔运算符的区别: &与&&和|对||的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆