I know the rules for &&
and ||
but what are &
and |
? Please explain these to me with an example.
我知道&和||的规则但是什么是&和|?请给我举个例子。
11 个解决方案
#1
109
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
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语言规范(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:
实际上,当两个输入都是布尔逻辑运算符时,这些运算符被认为是布尔逻辑运算符,它们的行为与条件运算符- and(&)和条件运算符- or(||)运算符类似,但它们不会短路,因此,下列操作符是安全的:
if((a != null) && (a.something == 3)){
}
This is not:
这不是:
if((a != null) & (a.something == 3)){
}
#2
96
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
#3
19
I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.
我知道这里有很多答案,但它们看起来都有点让人困惑。因此,在Java oracle研究指南中做了一些研究之后,我想到了三个不同的使用&&或&的场景。这三个场景是逻辑的、位的、布尔的和。
Logical AND: Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:
逻辑和:逻辑和(即条件和)使用&&运算符。它是短路的意思:如果左操作是假的,那么正确的操作数将不会被计算。例子:
int x = 0;
if (false && (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); // "0"
In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.
在上面的示例中,打印到x控制台的值将为0,因为if语句中的第一个操作数为false,因此java不需要计算(1 = +x),因此不会计算x。
Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:
位和:位并使用&运算符。它用于在值上预先形成一个位操作。通过观察二进制数的运算,我们更容易看到发生了什么。
int a = 5; // 5 in binary is 0101
int b = 12; // 12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4
As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.
正如您在示例中看到的,当数字5和12的二进制表示对齐时,按位排列和按位排列只会产生一个二进制数字,其中两个数字中的相同数字都是1。因此,0101 & 1100 == 0100。小数部分是5和12 = 4。
Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.
布尔和:现在布尔和运算符的行为与位、逻辑和和。我喜欢把它看作是在两个布尔值(或位)之间预形成位元,因此它使用&运算符。布尔值也可以是逻辑表达式的结果。
It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:
它返回真值或假值,与逻辑值和逻辑值很相似,但与逻辑值不同,它不会短路。原因是,为了使它以位形式表示,它必须知道左操作数和右操作数的值。这里的一个前女友:
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); //"1"
Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.
现在,当运行if语句时,将执行表达式(1 == +x),即使左操作数为false。因此输出x的值是1因为它是递增的。
This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.
这也适用于逻辑OR(||)、位或(|)和布尔OR(|),希望这能消除一些困惑。
#4
8
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.
运算符&&和||正在短路,这意味着如果左手表达式的值足以决定结果,它们将不会计算自己的右手表达式。
#5
4
& 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.
和|提供与&& ||运营商相同的结果。不同的是,当as &和||停止评估第一个条件是否足以决定结果时,它们总是评估表达式的两边。
#6
2
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中,单一运营商&,|,^,!依赖于操作数。如果两个操作数都是int,则执行位操作。如果两者都是布尔值,则执行“逻辑”操作。
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)){…}或类似的,如果(< 0)| |(b < 0)){…}
source: java programming lang 4th ed
源:java编程
#7
1
&
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).
和||只对布尔人操作(和短路,正如其他答案已经说过)。
#8
1
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.
也许知道位和位或运算符总是在条件和条件或条件或在同一个表达式中使用之前进行计算是有用的。
if ( (1>2) && (2>1) | true) // false!
#9
1
&& ; || 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日
#10
0
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.
当一个包含&&运算符的表达式被求值时,第一个操作数被求值。如果第一个操作数计算为false,则跳过第二个操作数的计算。
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,则计算第二个操作数。如果第二个操作数返回true,那么&&运算符将应用于第一个和第二个操作数。
Similar for | and ||.
类似于|和|。
#11
0
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 &&
.
虽然基本的区别是&主要用于长、int或字节的位操作,在这些操作中可以用于某种掩码,但是即使您使用它而不是使用逻辑和&,结果也可能有所不同。
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.
第一点非常简单,它不会导致bug,但是需要更多的时间。如果在一个条件语句中有几个不同的检查,那么将那些比较便宜或者更有可能失败的检查放在左边。
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。在删除一个构建对象之前,我们必须将一个Department对象的构建更改为另一个。我们还可以将操作状态返回为boolean (true = success)。然后:
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.
至于|| b,就等于!a && !b),如果a是真的,它就停止了,不需要更多的解释。
#1
109
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
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语言规范(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:
实际上,当两个输入都是布尔逻辑运算符时,这些运算符被认为是布尔逻辑运算符,它们的行为与条件运算符- and(&)和条件运算符- or(||)运算符类似,但它们不会短路,因此,下列操作符是安全的:
if((a != null) && (a.something == 3)){
}
This is not:
这不是:
if((a != null) & (a.something == 3)){
}
#2
96
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
#3
19
I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.
我知道这里有很多答案,但它们看起来都有点让人困惑。因此,在Java oracle研究指南中做了一些研究之后,我想到了三个不同的使用&&或&的场景。这三个场景是逻辑的、位的、布尔的和。
Logical AND: Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:
逻辑和:逻辑和(即条件和)使用&&运算符。它是短路的意思:如果左操作是假的,那么正确的操作数将不会被计算。例子:
int x = 0;
if (false && (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); // "0"
In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.
在上面的示例中,打印到x控制台的值将为0,因为if语句中的第一个操作数为false,因此java不需要计算(1 = +x),因此不会计算x。
Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:
位和:位并使用&运算符。它用于在值上预先形成一个位操作。通过观察二进制数的运算,我们更容易看到发生了什么。
int a = 5; // 5 in binary is 0101
int b = 12; // 12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4
As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.
正如您在示例中看到的,当数字5和12的二进制表示对齐时,按位排列和按位排列只会产生一个二进制数字,其中两个数字中的相同数字都是1。因此,0101 & 1100 == 0100。小数部分是5和12 = 4。
Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.
布尔和:现在布尔和运算符的行为与位、逻辑和和。我喜欢把它看作是在两个布尔值(或位)之间预形成位元,因此它使用&运算符。布尔值也可以是逻辑表达式的结果。
It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:
它返回真值或假值,与逻辑值和逻辑值很相似,但与逻辑值不同,它不会短路。原因是,为了使它以位形式表示,它必须知道左操作数和右操作数的值。这里的一个前女友:
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); //"1"
Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.
现在,当运行if语句时,将执行表达式(1 == +x),即使左操作数为false。因此输出x的值是1因为它是递增的。
This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.
这也适用于逻辑OR(||)、位或(|)和布尔OR(|),希望这能消除一些困惑。
#4
8
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.
运算符&&和||正在短路,这意味着如果左手表达式的值足以决定结果,它们将不会计算自己的右手表达式。
#5
4
& 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.
和|提供与&& ||运营商相同的结果。不同的是,当as &和||停止评估第一个条件是否足以决定结果时,它们总是评估表达式的两边。
#6
2
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中,单一运营商&,|,^,!依赖于操作数。如果两个操作数都是int,则执行位操作。如果两者都是布尔值,则执行“逻辑”操作。
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)){…}或类似的,如果(< 0)| |(b < 0)){…}
source: java programming lang 4th ed
源:java编程
#7
1
&
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).
和||只对布尔人操作(和短路,正如其他答案已经说过)。
#8
1
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.
也许知道位和位或运算符总是在条件和条件或条件或在同一个表达式中使用之前进行计算是有用的。
if ( (1>2) && (2>1) | true) // false!
#9
1
&& ; || 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日
#10
0
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.
当一个包含&&运算符的表达式被求值时,第一个操作数被求值。如果第一个操作数计算为false,则跳过第二个操作数的计算。
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,则计算第二个操作数。如果第二个操作数返回true,那么&&运算符将应用于第一个和第二个操作数。
Similar for | and ||.
类似于|和|。
#11
0
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 &&
.
虽然基本的区别是&主要用于长、int或字节的位操作,在这些操作中可以用于某种掩码,但是即使您使用它而不是使用逻辑和&,结果也可能有所不同。
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.
第一点非常简单,它不会导致bug,但是需要更多的时间。如果在一个条件语句中有几个不同的检查,那么将那些比较便宜或者更有可能失败的检查放在左边。
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。在删除一个构建对象之前,我们必须将一个Department对象的构建更改为另一个。我们还可以将操作状态返回为boolean (true = success)。然后:
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.
至于|| b,就等于!a && !b),如果a是真的,它就停止了,不需要更多的解释。