布尔运算符的差异:& vs&&和| vs || [英] Differences in boolean operators: & vs && and | vs ||

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

问题描述

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

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语言规范( 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.

实际上,当两个输入都是布尔值时,运算符被认为是布尔逻辑运算符,其行为类似于Conditional-And(&& )和Conditional-Or( || )运算符除了它们没有短路这样的事实,所以以下是安全的:

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)){
}

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

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