Differences in Boolean Operators: & VS && and | VS ||

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.

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

& and && behaving very differently in R

The '&' here returns a vector, It is 'and' operator between each pair of 1 <= mhbins$val and mhbins$val <= 7
While '&&' looks at only first pair of 1 <= mhbins$val and mhbins$val <= 7

Example

c(TRUE,TRUE) & c(FALSE,TRUE) `returns <[1] FALSE  TRUE>`
c(TRUE,TRUE) && c(FALSE,TRUE) `returns <[1] FALSE>`

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

In R programming, what's the difference between & vs &&, and | vs ||

they can only handle a single logical test on each side of the operator

a <- c(T, F, F, F)
b <- c(T, F, F, F)
a && b

Returns
[1] TRUE

Because only the first element of a and b are tested!

Edit:

Consider the following, where we 'rotate' a and b after each && test:

a <- c(T, F, T, F)
b <- c(T, F, F, T)
for (i in seq_along(a)){
cat(paste0("'a' is: ", paste0(a, collapse=", "), " and\n'b' is: ", paste0(b, collapse=", "),"\n"))
print(paste0("'a && b' is: ", a && b))
a <- c(a[2:length(a)], a[1])
b <- c(b[2:length(b)], b[i])
}

Gives us:

'a' is: TRUE, FALSE, TRUE, FALSE and
'b' is: TRUE, FALSE, FALSE, TRUE
[1] "'a && b' is: TRUE"
'a' is: FALSE, TRUE, FALSE, TRUE and
'b' is: FALSE, FALSE, TRUE, TRUE
[1] "'a && b' is: FALSE"
'a' is: TRUE, FALSE, TRUE, FALSE and
'b' is: FALSE, TRUE, TRUE, FALSE
[1] "'a && b' is: FALSE"
'a' is: FALSE, TRUE, FALSE, TRUE and
'b' is: TRUE, TRUE, FALSE, TRUE
[1] "'a && b' is: FALSE"

Additionally, &&, || stops as soon as the expression is clear:

FALSE & a_not_existing_object
TRUE | a_not_existing_object

Returns:

Error: object 'a_not_existing_object' not found
Error: object 'a_not_existing_object' not found

But:

FALSE && a_not_existing_object
TRUE || a_not_existing_object

Returns:

[1] FALSE

[1] TRUE

Because anything after FALSE AND something (and TRUE OR something) becomes FALSE and TRUE respectively

This last behavior of && and || is especially useful if you want to check in your control-flow for an element that may not exist:

if (exists(a_not_existing_object) && a_not_existing_object > 42) {...}

This way the evaluation stops after the first expression evaluates to FALSE and the a_not_existing_object > 42 part is not even atempted!

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

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



Related Topics



Leave a reply



Submit