Why Do We Usually Use || Over |? What Is the Difference

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

Difference between OR operator || and | in Java?

This is simple. http://www.roseindia.net/help/java/o/java-operator.shtml says:

OR operator is a kind of a conditional operators, which is represented
by | symbol. It returns either true or false value based on the state
of the variables i.e. the operations using conditional operators are
performed between the two boolean expressions.

The OR operator (|) is similar to the Conditional-OR operator (||) and
returns true, if one or another of its operand is true.

Note: In || operator if have more than one condition and if first condition return true then other conditions ignored but in | operator all condition examin.

There are more information on http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Differences in boolean operators: & vs && and | vs ||

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.

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:

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."

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.

What is the difference between & and && in Java?

& <-- verifies both operands

&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

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.

What is short circuiting and how is it used when programming in Java?

Short-circuiting is where an expression is stopped being evaluated as soon as its outcome is determined. So for instance:

if (a == b || c == d || e == f) {
// Do something
}

If a == b is true, then c == d and e == f are never evaluated at all, because the expression's outcome has already been determined. if a == b is false, then c == d is evaluated; if it's true, then e == f is never evaluated. This may not seem to make any difference, but consider:

if (foo() || bar() || baz()) {
// Do something
}

If foo() returns true, then bar and baz are never called, because the expression's outcome has already been determined. So if bar or baz has some other effect than just returning something (a side effect), those effects never occur.

One great example of short-circuiting relates to object references:

if (a != null && a.getFoo() != 42) {
// Do something
}

a.getFoo() would normally throw a NullPointerException if a were null, but because the expression short-circuits, if a != null is false, the a.getFoo() part never happens, so we don't get an exception.

Note that not all expressions are short-circuited. The || and && operators are short-circuited, but | and & are not, nor are * or /; in fact most operators are not.

Difference between count = count + n&1 and count += n&1

Precedence in C++ or any other programming languages determines the order of evaluation of those instructions, some go from right to left, some are evaluated first before the other. So, in this case, your += was evaluated after the & (AND) operator, and that was the reason for your wrong answer when is done this way

count = count + n & 1;

Because in the code above, the + is evaluated then the AND was then next. You can either put a bracket around it like this below

count = count + (n & 1);

Since the bracket operator has higher precedence it will always ensure you get the right results.
You can learn more about precedence here. You will see the order of evaluation for each operator.

The associativity of an operator is a property that determines how
operators of the same precedence are grouped in the absence of
parentheses. This affects how an expression is evaluated.

And you can always check your C++ or C reference Manuals to learn more about precedence.
https://en.cppreference.com/w/cpp/language/operator_precedence

Javascript: Why use Logical Operators along with Comparison Operator?

if (0 <= totalMark < 40) {

This doesn't do what you think it does. You're expecting it to check whether totalMark is in the range from [0, 40). But what it's really going to do is evaluate it one piece at a time. It's going to check 0 <= totalMark and get either a true or a false.

Let's say totalMark is a negative number, so you get false from this piece. The next thing it will compare is false < 40. That doesn't make much sense, but javascript will do its best. Following the obscure rules of javascript type coercion, false gets treated as 0 so it checks 0 < 40 which is true. Therefore, 0 <= totalMark < 40 resolves to true when totalMark is a negative number. In fact, if you walk through the other possibilities, it will always result in true.

In short, these comparison operators can only look at 2 things at once. And then you use &&'s and ||'s to build up something larger.



Related Topics



Leave a reply



Submit