[英]Why Logical operators, when there is Bitwise operators in java
I know that the Bitwise operators &, | 我知道Bitwise运算符&,| and ^ are EITHER bitwise operators OR logical operators ... depending on the types of the operands.
和^是按位运算符或逻辑运算符...取决于操作数的类型。
If the operands are integers, the operators are bitwise.
如果操作数是整数,则运算符是按位的。 If they are booleans, then the operators are logical.
如果他们是布尔,那么运营商是合乎逻辑的。
Then why there are Logical operators &&,|| 那么为什么有逻辑运算符&&,|| and!
和! ?
? I believe there will be some situations where we can use only logical operator , and so they are.
我相信在某些情况下我们只能使用逻辑运算符 ,因此它们是。
So, can anyone explain such a situation? 那么,任何人都可以解释这种情况吗? Or any advantage over bitwise ops.
或者比按位操作有任何优势。
Operators && and || 运营商&&和|| evaluates lazily .
懒洋洋地评估。 This means that only one side might be evaluated.
这意味着只能评估一方。
Operators & and | 运营商&和| evaluates eagerly , this means that always both sides are evaluated.
热切地评估,这意味着始终对双方进行评估。
It is very important when you expressions have side effects. 当表达式有副作用时,这一点非常重要。
Examples 例子
x = 0;
(x++ == 0) || (x++ == 1); // x is 1
x = 0;
(x++ == 0) | (x++ == 1); // x is 2
Logical operators &&,|| 逻辑运算符&&,|| etc let you
short circuit
the logic. 让你
short circuit
逻辑。
1==1 || complexMethod(/*param*/)
complexMethod() will not execute. complexMethod() 不会执行。
1==1 | complexMethod(/*param*/)
complexMethod() will execute. complexMethod() 将执行。
Short circuiting basically means the condition will be evaluated only up to where it is necessary and not beyond that . 短路基本上意味着只有在必要的情况下才会评估条件,而不是在此之外 。
Uses in Short-circuit evaluation like 用于短路评估之类的
Ex: 例如:
see &&
看
&&
if(Condition1 && condition2){
}
and ||
和
||
if(Condition1 || condition2){
}
in these cases 在这些情况下
in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression:
其中第二个参数仅在第一个参数不足以确定表达式的值时执行或计算:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.