Java 布尔运算符的区别:& vs && 和 | 对||
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4014535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Differences in boolean operators: & vs && and | vs ||
提问by Sumithra
I know the rules for &&
and ||
but what are &
and |
? Please explain these to me with an example.
我知道&&
and的规则,||
但是&
and 是|
什么?请用一个例子向我解释这些。
采纳答案by Justin Niessner
Those are the bitwise AND and bitwise OR operators.
这些是按位 AND 和按位 OR 运算符。
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
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.
感谢 Carlos 在 Java Language Spec ( 15.22.1, 15.22.2) 中指出了有关运算符基于其输入的不同行为的适当部分。
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:
实际上,当两个输入都是布尔值时,这些运算符被认为是布尔逻辑运算符,其行为类似于 Conditional-And ( &&
) 和 Conditional-Or ( ||
) 运算符,只是它们不会短路,因此虽然以下是安全的:
if((a != null) && (a.something == 3)){
}
This is not:
这不是:
if((a != null) & (a.something == 3)){
}
"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
不是时才会检查第二个条件null
(否则整个语句将返回false,无论如何检查以下条件都是没有实际意义的),因此该语句a.something
不会引发异常,或者被认为是“安全的” .”
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.
在&
操作者始终检查子句中的每个状态,所以在上述例子中,a.something
也可以当被评估a
事实上是一个null
值,产生一个异常。
回答by Tassos Bassoukos
The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result.
运算符 && 和 || 是短路的,这意味着如果左侧表达式的值足以确定结果,它们将不会评估其右侧表达式。
回答by Bruno
&
and |
are bitwise operators on integral types (e.g. int
): http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
&
并且|
是整数类型的按位运算符(例如int
):http: //download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
&&
and ||
operate on booleans only (and short-circuit, as other answers have already said).
&&
并且||
仅对布尔值进行操作(和短路,正如其他答案已经说过的那样)。
回答by Brian Scott
& and | provide the same outcome as the && and || operators. The difference is that they always evaluate both sides of the expression where as && and || stop evaluating if the first condition is enough to determine the outcome.
& 和 | 提供与 && 和 || 相同的结果 运营商。不同之处在于它们总是计算表达式的两边 where as && 和 || 停止评估第一个条件是否足以确定结果。
回答by Torres
I think you're talking about the logical meaning of both operators, here you have a table-resume:
我认为您在谈论两个运算符的逻辑含义,这里有一个表格简历:
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
短路求值、最小求值或 McCarthy 求值(在 John McCarthy 之后)是某些编程语言中某些布尔运算符的语义,其中仅当第一个参数不足以确定第一个参数的值时才执行或计算第二个参数表达式:当 AND 函数的第一个参数计算结果为 false 时,整个值必须为 false;并且当 OR 函数的第一个参数计算为真时,整体值必须为真。
Not Safemeans the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.
Not Safe意味着运算符总是检查子句中的每个条件,因此在上面的示例中,当 x 实际上是 0 值时,可能会计算 1/x,从而引发异常。
回答by alexmeia
Maybe it can be useful to know that the bitwise AND and bitwise OR operators are always evaluated before conditional AND and conditional OR used in the same expression.
了解按位 AND 和按位 OR 运算符始终在同一表达式中使用的条件 AND 和条件 OR 之前计算可能很有用。
if ( (1>2) && (2>1) | true) // false!
回答by RishiKesh Pathak
If an expression involving the Boolean &operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand.
如果计算涉及布尔&运算符的表达式,则计算两个操作数。然后将 & 运算符应用于操作数。
When an expression involving the &&operator is evaluated, the first operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
当计算涉及&&运算符的表达式时,将计算第一个操作数。如果第一个操作数的计算结果为假,则跳过第二个操作数的计算。
If the first operand returns a value of true then the second operand is evaluated. If the second operand returns a value of true then && operator is then applied to the first and second operands.
如果第一个操作数返回真值,则计算第二个操作数。如果第二个操作数返回 true 值,则 && 运算符将应用于第一个和第二个操作数。
Similar for | and ||.
类似的 | 和||。
回答by Vlasec
While the basic difference is that &
is used for bitwise operations mostly on long
, int
or byte
where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&
.
虽然基本的区别在于它&
主要用于按位运算long
,int
或者byte
它可以用于某种掩码,但即使您使用它而不是逻辑 ,结果也可能不同&&
。
The difference is more noticeable in some scenarios:
在某些情况下,差异更为明显:
- Evaluating some of the expressions is time consuming
- Evaluating one of the expression can be done only if the previous one was true
- The expressions have some side-effect (intended or not)
- 评估一些表达式很耗时
- 仅当前一个表达式为真时才能对其中一个表达式求值
- 表达式有一些副作用(有意或无意)
First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.
第一点很简单,它不会导致错误,但需要更多时间。如果你在一个条件语句中有几个不同的检查,把那些更便宜或更可能失败的放在左边。
For second point, see this example:
对于第二点,请参见此示例:
if ((a != null) & (a.isEmpty()))
This fails for null
, as evaluating the second expression produces a NullPointerException
. Logical operator &&
is lazy, if left operand is false, the result is false no matter what right operand is.
这失败了null
,因为评估第二个表达式会产生一个NullPointerException
。逻辑运算符&&
是惰性的,如果左操作数为假,则无论右操作数是什么,结果都是假的。
Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:
第三点的示例——假设我们有一个使用 DB 的应用程序,没有任何触发器或级联。在移除 Building 对象之前,我们必须将 Department 对象的建筑物更改为另一个建筑物。假设操作状态以布尔值形式返回(true = 成功)。然后:
if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))
This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&
, it works as intended and it stops after first failure.
即使部门更新由于某种原因失败,这也会评估两个表达式并因此执行建筑物删除。使用&&
,它按预期工作,并在第一次失败后停止。
As for a || b
, it is equivalent of !(!a && !b)
, it stops if a
is true, no more explanation needed.
至于a || b
,相当于!(!a && !b)
,a
为真则停止,无需多解释。
回答by aaron p.
In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.
在 Java 中,单运算符 &、|、^、! 取决于操作数。如果两个操作数都是整数,则执行按位运算。如果两者都是布尔值,则执行“逻辑”操作。
If both operands mismatch, a compile time error is thrown.
如果两个操作数不匹配,则会引发编译时错误。
The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:
双运算符 &&, || 行为与它们的单个对应物相似,但两个操作数都必须是条件表达式,例如:
if (( a < 0 ) && ( b < 0 )) { ... } or similarly, if (( a < 0 ) || ( b < 0 )) { ... }
if (( a < 0 ) && ( b < 0 )) { ... } 或类似的, if (( a < 0 ) || ( b < 0 )) { ... }
source: java programming lang 4th ed
来源:java 编程语言第 4 版
回答by Nickhil
&& ; || are logical operators.... short circuit
&; || 是逻辑运算符....短路
& ; | are boolean logical operators.... Non-short circuit
&; | 是布尔逻辑运算符.... 非短路
Moving to differences in execution on expressions. Bitwise operators evaluate both sides irrespective of the result of left hand side. But in the case of evaluating expressions with logical operators, the evaluation of the right hand expression is dependent on the left hand condition.
移至表达式执行的差异。无论左侧的结果如何,按位运算符都会评估两侧。但是在使用逻辑运算符评估表达式的情况下,右侧表达式的评估取决于左侧条件。
For Example:
例如:
int i = 25;
int j = 25;
if(i++ < 0 && j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
This will print i=26 ; j=25, As the first condition is false the right hand condition is bypassed as the result is false anyways irrespective of the right hand side condition.(short circuit)
这将打印 i=26 ; j=25,由于第一个条件为假,右手条件被绕过,因为无论右手边条件如何,结果都是假的。(短路)
int i = 25;
int j = 25;
if(i++ < 0 & j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
But, this will print i=26; j=26,
但是,这将打印 i=26; j=26,