What is the difference between the | and || or operators?
Just like the &
and &&
operator, the double Operator is a "short-circuit" operator.
For example:
if(condition1 || condition2 || condition3)
If condition1 is true, condition 2 and 3 will NOT be checked.
if(condition1 | condition2 | condition3)
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
if(class != null && class.someVar < 20)
If class is null, the if-statement will stop after class != null
is false. If you only use &, it will try to check class.someVar
and you get a nice NullReferenceException
. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.
No one ever uses the single &
or |
operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The &
operator does "run these 3 functions, and if one of them returns false, execute the else block", while the |
does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the |
and &
operator though: Bitwise Operations.
Difference between || and ?? operators
The main difference is that nullish coalescing(??)
operator will only give the result as the right operand only if the left operand is either null
or undefined
.
Whereas the OR(||)
operator will give the result as right operand for all the falsy values of the left operand.
Below are some examples
- Snippet 1: With
0
as input
const a = 0;
// a || 10 --> Will result in 10, as || operator considers 0 as falsy value and resulting the right side operand
console.log(`a || 10 = ${a || 10}`);
// a ?? 10 --> Will result in 0, as ?? operator considers 0 as truthy value and resulting the left side operand
console.log(`a ?? 10 = ${a ?? 10}`);
What is the difference between the | and || operators?
|
is a bitwise or, ||
is a boolean or.
What's the difference between ( | ) and ( || )?
|
is a bitwise or, ||
is a logical or.
A bitwise or takes the two numbers and compares them on a bit-by-bit basis, producing a new integer which combines the 1 bits from both inputs. So 0101 | 1010
would produce 1111
.
A logical or ||
checks for the "truthiness" of a value (depends on the type, for integers 0 is false and non-zero is true). It evaluates the statement left to right, and returns the first value which is truthy. So 0101 || 1010
would return 0101
which is truthy, therefore the whole statement is said to be true.
The same type of logic applies for &
vs &&
. 0101 & 1010
= 0000
. However 0101 && 1010
evaluates to 1010
(&&
returns the last truthy value so long as both operands are truthy).
Why do we usually use || over |? What is the difference?
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
Php: What is the difference between | and || operator
|
is a bitwise or, ||
is a logical or. |
operates on binary values whereas ||
operates on boolean ones.
E.g. 5 | 3
is 0101 OR 0011
which is 0111
which is 7, whereas True || False
is True and False || False
is False.
what is the difference between `| `and` || `in java?
a || b
never evaluates b
if a
evaluates to true.
What do the & and | operators do? How are they different from && and ||? Swift
See the Wikipedia page on Bitwise Operation and the Swift documentation for bitwise operators.
These are bitwise operators. &
is bitwise AND and |
is bitwise OR.
See these examples:
0011 (decimal 3)
AND 0010 (decimal 2)
= 0010 (decimal 2)
0101 (decimal 5)
OR 0011 (decimal 3)
= 0111 (decimal 7)
Source: Wikipedia
The uses of bitwise operators have been discussed before on StackOverflow:
- practical applications of bitwise operations
- Using bitwise operations
A use of bitwise XOR (not in your question, but a cool logic gate anyway) that caught my eye (by @Vilx- here) (I don't know how it works, but the answer was accepted and up-voted 34 times)
EDIT: If you want to know how it works, there's a nice simple proof over on XOR swap algorithm - Wikipedia
Swapping two integer variables without an intermediary variable:
A = A^B // A is now XOR of A and B
B = A^B // B is now the original A
A = A^B // A is now the original B
If these don't help, the Wikipedia page I already linked to twice in this post has an Applications section, but they don't really apply to higher-level languages (unless for some reason you want to optimize your arithmetic to use only bitwise operations).
Related Topics
Trying to Replace Parts of String Start with Same Search Chars
Laravel Password Validation Rule
Laravel: Where to Store Global Arrays Data and Constants
Nginx Issues Http 499 Error After 60 Seconds Despite Config. (PHP and Aws)
How to Perform Multiple Guzzle Requests at the Same Time
How to Do a Curl Request to the Same Server
Mysqli Prepare Statement - Returning False, But Why
Install PHP-Mcrypt on Centos 6
Php: How to Check If a Date Is Today, Yesterday or Tomorrow
PHP Regex for Validating a Url
How to Create Multi-Dimensional Array from a List
Converting a Postman Request to Curl
How to Display the Users Profile Pic Using the Facebook Graph API
Getting Order Data After Successful Checkout Hook