可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I\'m just wondering why we usually use logical OR ||
between two booleans not bitwise OR |
, though they are both working well.
I mean, look at the following:
if(true | true) // pass
if(true | false) // pass
if(false | true) // pass
if(false | false) // no pass
if(true || true) // pass
if(true || false) // pass
if(false || true) // pass
if(false || false) // no pass
Can we use |
instead of ||
? Same thing with &
and &&
.
回答1:
If you use the ||
and &&
forms, rather than the |
and &
forms of these operators, Java will not bother to evaluate the right-hand operand alone.
It\'s a matter of if you want to short-circuit the evaluation or not -- most of the time you want to.
A good way to illustrate the benefits of short-circuiting would be to consider the following example.
Boolean b = true;
if(b || foo.timeConsumingCall())
{
//we entered without calling timeConsumingCall()
}
Another benefit, as Jeremy and Peter mentioned, for short-circuiting is the null reference check:
if(string != null && string.isEmpty())
{
//we check for string being null before calling isEmpty()
}
more info
回答2:
|
does not do short-circuit evaluation in boolean expressions. ||
will stop evaluating if the first operand is true, but |
won\'t.
In addition, |
can be used to perform the bitwise-OR operation on byte/short/int/long values. ||
cannot.
回答3:
So just to build on the other answers with an example, short-circuiting is crucial in the following defensive checks:
if (foo == null || foo.isClosed()) {
return;
}
if (bar != null && bar.isBlue()) {
foo.doSomething();
}
Using |
and &
instead could result in a NullPointerException
being thrown here.
回答4:
Logical ||
and &&
check the right hand side only if necessary. The |
and &
check both all the time.
For example:
int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...
Rewrite it:
int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i doesn\'t = 10
...
Another example:
int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...
Rewrite it:
int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...
回答5:
Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:
boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c
Be careful when mixing them.
回答6:
In addition to short-circuiting, another thing to keep in mind is that doing a bitwise logic operation on values that can be other than 0 or 1 has a very different meaning than conditional logic. While it USUALLY is the same for |
and ||
, with &
and &&
you get very different results (e.g. 2 & 4
is 0/false while 2 && 4
is 1/true).
If the thing you\'re getting from a function is actually an error code and you\'re testing for non-0-ness, this can matter quite a lot.
This isn\'t as much of an issue in Java where you have to explicitly typecast to boolean or compare with 0 or the like, but in other languages with similar syntax (C/C++ et al) it can be quite confusing.
Also, note that & and | can only apply to integer-type values, and not everything that can be equivalent to a boolean test. Again, in non-Java languages, there are quite a few things that can be used as a boolean with an implicit != 0
comparison (pointers, floats, objects with an operator bool()
, etc.) and bitwise operators are almost always nonsensical in those contexts.
回答7:
The only time you would use |
or &
instead of ||
or &&
is when you have very simple boolean expressions and the cost of short cutting (i.e. a branch) is greater than the time you save by not evaluating the later expressions.
However, this is a micro-optimisation which rarely matters except in the most low level code.
回答8:
|| is the logical or operator while | is the bitwise or operator.
boolean a = true;
boolean b = false;
if (a || b) {
}
int a = 0x0001;
a = a | 0x0002;
回答9:
a | b: evaluate b in any case
a || b: evaluate b only if a evaluates to false
回答10:
In Addition to the fact that | is a bitwise-operator: || is a short-circuit operator - when one element is false, it will not check the others.
if(something || someotherthing)
if(something | someotherthing)
if something is TRUE, || will not evaluate someotherthing, while | will do. If the variables in your if-statements are actually function calls, using || is possibly saving a lot of performance.
回答11:
| is the binary or operator
|| is the logic or operator
回答12:
The operators ||
and &&
are called conditional operators, while |
and &
are called bitwise operators. They serve different purposes.
Conditional operators works only with expressions that statically evaluate to boolean
on both left- and right-hand sides.
Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.
回答13:
A side note: Java has |= but not an ||=
An example of when you must use || is when the first expression is a test to see if the second expression would blow up. e.g. Using a single | in hte following case could result in an NPE.
public static boolean isNotSet(String text) {
return text == null || text.length() == 0;
}
回答14:
The other answers have done a good job of covering the functional difference between the operators, but the answers could apply to just about every single C-derived language in existence today. The question is tagged with java, and so I will endeavor to answer specifically and technically for the Java language.
&
and |
can be either Integer Bitwise Operators, or Boolean Logical Operators. The syntax for the Bitwise and Logical Operators (§15.22) is:
AndExpression:
EqualityExpression
AndExpression & EqualityExpression
ExclusiveOrExpression:
AndExpression
ExclusiveOrExpression ^ AndExpression
InclusiveOrExpression:
ExclusiveOrExpression
InclusiveOrExpression | ExclusiveOrExpression
The syntax for EqualityExpression
is defined in §15.21, which requires RelationalExpression
defined in §15.20, which in turn requires ShiftExpression
and ReferenceType
defined in §15.19 and §4.3, respectively. ShiftExpression
requires AdditiveExpression
defined in §15.18, which continues to drill down, defining the basic arithmetic, unary operators, etc. ReferenceType
drills down into all the various ways to represent a type. (While ReferenceType
does not include the primitive types, the definition of primitive types is ultimately required, as they may be the dimension type for an array, which is a ReferenceType
.)
The Bitwise and Logical Operators have the following properties:
- These operators have different precedence, with
&
having the highest precedence and |
the lowest precedence.
- Each of these operators is syntactically left-associative (each groups left-to-right).
- Each operator is commutative if the operand expressions have no side effects.
- Each operator is associative.
- The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type
boolean
. All other cases result in a compile-time error.
The distinction between whether the operator serves as a bitwise operator or a logical operator depends on whether the operands are \"convertible to a primitive integral type\" (§4.2) or if they are of types boolean
or Boolean
(§5.1.8).
If the operands are integral types, binary numeric promotion (§5.6.2) is performed on both operands, leaving them both as either long
s or int
s for the operation. The type of the operation will be the type of the (promoted) operands. At that point, &
will be bitwise AND, ^
will be bitwise exclusive OR, and |
will be bitwise inclusive OR. (§15.22.1)
If the operands are boolean
or Boolean
, the operands will be subject to unboxing conversion if necessary (§5.1.8), and the type of the operation will be boolean
. &
will result in true
if both operands are true
, ^
will result in true
if both operands are different, and |
will result in true
if either operand is true
. (§15.22.2)
In contrast, &&
is the \"Conditional-And Operator\" (§15.23) and ||
is the \"Conditional-Or Operator\" (§15.24). Their syntax is defined as:
ConditionalAndExpression:
InclusiveOrExpression
ConditionalAndExpression && InclusiveOrExpression
ConditionalOrExpression:
ConditionalAndExpression
ConditionalOrExpression || ConditionalAndExpression
&&
is like &
, except that it only evaluates the right operand if the left operand is true
. ||
is like |
, except that it only evaluates the right operand if the left operand is false
.
Conditional-And has the following properties:
- The conditional-and operator is syntactically left-associative (it groups left-to-right).
- The conditional-and operator is fully associative with respect to both side effects and result value. That is, for any expressions
a
, b
, and c
, evaluation of the expression ((a) && (b)) && (c)
produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a) && ((b) && (c))
.
- Each operand of the conditional-and operator must be of type
boolean
or Boolean
, or a compile-time error occurs.
- The type of a conditional-and expression is always
boolean
.
- At run time, the left-hand operand expression is evaluated first; if the result has type
Boolean
, it is subjected to unboxing conversion (§5.1.8).
- If the resulting value is
false
, the value of the conditional-and expression is false
and the right-hand operand expression is not evaluated.
- If the value of the left-hand operand is
true
, then the right-hand expression is evaluated; if the result has type Boolean
, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-and expression.
- Thus,
&&
computes the same result as &
on boolean
operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
Conditional-Or has the following properties:
- The conditional-or operator is syntactically left-associative (it groups left-to-right).
- The conditional-or operator is fully associative with respect to both side effects and result value. That is, for any expressions
a
, b
, and c
, evaluation of the expression ((a) || (b)) || (c)
produces the same result, with the same side effects occurring in the same order, as evaluation of the expression (a) || ((b) || (c))
.
- Each operand of the conditional-or operator must be of type
boolean
or Boolean
, or a compile-time error occurs.
- The type of a conditional-or expression is always
boolean
.
- At run time, the left-hand operand expression is evaluated first; if the result has type
Boolean
, it is subjected to unboxing conversion (§5.1.8).
- If the resulting value is
true
, the value of the conditional-or expression is true
and the right-hand operand expression is not evaluated.
- If the value of the left-hand operand is
false
, then the right-hand expression is evaluated; if the result has type Boolean
, it is subjected to unboxing conversion (§5.1.8). The resulting value becomes the value of the conditional-or expression.
- Thus,
||
computes the same result as |
on boolean
or Boolean
operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
In short, as @JohnMeagher has repeatedly pointed out in the comments, &
and |
are, in fact, non-short-circuiting boolean operators in the specific case of the operands being either boolean
or Boolean
. With good practices (ie: no secondary effects), this is a minor difference. When the operands aren\'t boolean
s or Boolean
s, however, the operators behave very differently: bitwise and logical operations simply don\'t compare well at the high level of Java programming.
回答15:
1).(expression1 | expression2), | operator will evaluate expression2 irrespective of whether the result of expression1 is true or false.
Example:
class Or
{
public static void main(String[] args)
{
boolean b=true;
if (b | test());
}
static boolean test()
{
System.out.println(\"No short circuit!\");
return false;
}
}
2).(expression1 || expression2), || operator will not evaluate expression2 if expression1 is true.
Example:
class Or
{
public static void main(String[] args)
{
boolean b=true;
if (b || test())
{
System.out.println(\"short circuit!\");
}
}
static boolean test()
{
System.out.println(\"No short circuit!\");
return false;
}
}
回答16:
|| returns a boolean value by OR\'ing two values (Thats why its known as a LOGICAL or)
IE:
if (A || B)
Would return true if either A or B is true, or false if they are both false.
| is an operator that performs a bitwise operation on two values. To better understand bitwise operations, you can read here:
http://en.wikipedia.org/wiki/Bitwise_operation
回答17:
One main difference is that || and && exhibit \"short-circuiting\", so the RHS will only be evaluated if needed.
For e.g.
if (a || b) {
path1...
} else {
path2..
}
Above if a is true then b will not be tested and path1 is executed. If | was used then both sides would be evaluated even if \'a\' is true.
See Here and here, for a little more information.
Hope this helps.
回答18:
Non short-circuiting can be useful. Sometimes you want to make sure that two expressions evaluate. For example, say you have a method that removes an object from two separate lists. You might want to do something like this:
class foo {
ArrayList<Bar> list1 = new ArrayList<Bar>();
ArrayList<Bar> list2 = new ArrayList<Bar>();
//Returns true if bar is removed from both lists, otherwise false.
boolean removeBar(Bar bar) {
return (list1.remove(bar) & list2.remove(bar));
}
}
If your method instead used the conditional operand, it would fail to remove the object from the second list if the first list returned false.
//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
return (list1.remove(bar) && list2.remove(bar));
}
It\'s not amazingly useful, and (as with most programming tasks) you could achieve it with other means. But it is a use case for bitwise operands.
回答19:
The basic difference between them is that | first converts the values to binary then performs the bit wise or operation. Meanwhile, || does not convert the data into binary and just performs the or expression on it\'s original state.
int two = -2; int four = -4;
result = two | four; // bitwise OR example
System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));
Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110
Read more: http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk
回答20:
When I had this question I created test code to get an idea about this.
public class HelloWorld{
public static boolean bool(){
System.out.println(\"Bool\");
return true;
}
public static void main(String []args){
boolean a = true;
boolean b = false;
if(a||bool())
{
System.out.println(\"If condition executed\");
}
else{
System.out.println(\"Else condition executed\");
}
}
}
In this case, we only change left side value of if condition adding a or b.
||
Scenario , when left side true [if(a||bool())]
output \"If condition executed\"
||
Scenario , when left side false [if(b||bool())]
Output-
Bool
If condition executed
Conclusion of ||
When use ||
, right side only check when the left side is false.
|
Scenario , when left side true [if(a|bool())]
Output-
Bool
If condition executed
|
Scenario , when left side false [if(b|bool())]
Output-
Bool
If condition executed
Conclusion of |
When use |
, check both left and right side.
回答21:
| = bitwise or, || = logic or
回答22:
usually I use when there is pre increment and post increment operator. Look at the following code:
package ocjpPractice;
/**
* @author tithik
*
*/
public class Ex1 {
public static void main(String[] args) {
int i=10;
int j=9;
int x=10;
int y=9;
if(i==10 | ++i>j){
System.out.println(\"it will print in first if\");
System.out.println(\"i is: \"+i);
}
if(x==10 ||++x>y){
System.out.println(\"it will print in second if\");
System.out.println(\"x is: \"+x);
}
}
}
output:
it will print in first if
i is: 11
it will print in second if
x is: 10
both if
blocks are same but result is different.
when there is |
, both the conditions will be evaluated. But if it is ||
, it will not evaluate second condition as the first condition is already true.
回答23:
There are many use cases suggesting why should you go for ||
rather than |
. Some use cases have to use |
operator to check all the conditions.
For example, if you want to check form validation and you want to show the user all the invalid fields with error texts rather than just a first invalid field.
||
operator would be,
if(checkIfEmpty(nameField) || checkIfEmpty(phoneField) || checkIfEmpty(emailField)) {
// invalid form with one or more empty fields
}
private boolean checkIfEmpty(Widget field) {
if(field.isEmpty()) {
field.setErrorMessage(\"Should not be empty!\");
return true;
}
return false;
}
So with above snippet, if user submits the form with ALL empty fields, ONLY nameField
would be shown with error message. But, if you change it to,
if(checkIfEmpty(nameField) | checkIfEmpty(phoneField) | checkIfEmpty(emailField)) {
// invalid form with one or more empty fields
}
It will show proper error message on the each field irrespective of true
conditions.
回答24:
|| is a logical or and | is a bit-wise or.
回答25:
Java operators
| is bitwise or, || is logical or.
回答26:
Take a look at:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
| is bitwise inclusive OR
|| is logical OR
回答27:
| is a bitwise operator. || is a logical operator.
One will take two bits and or them.
One will determine truth (this OR that) If this is true or that is true, then the answer is true.
Oh, and dang people answer these questions fast.