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 ( &&, -a, ||, -o ) in Bash
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.[
is not special syntax. It's actually a command with the name[
, also known astest
. Since[
is just a regular command, it uses-a
and-o
for its and and or operators. It can't use&&
and||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
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".
What's the difference between or and | in ruby?
The |
operator is a binary mathematical operator, that is it does a binary OR and works on a numerical level:
1 | 2
# => 3
4 | 3
# => 7
1 | 2 | 3
# => 3
This is because it's manipulating individual values as if they were binary:
0b01 | 0b10
# => 3 (0b11)
The ||
operator is a logical one, that is it returns the first value that's logically true. In Ruby only literal nil
and false
values evaluates as logically false, everything else, including 0
, empty strings and arrays, is true.
So:
1 || 2
# => 1
0 || 1
# => 0
The or
operator works almost exactly the same as ||
except it's at a much lower precedence. That means other operators are evaluated first which can lead to some problems if you're not anticipating this:
a = false || true
# => true
a
# => true
a = false or true
# => true
a
# => false
This is because it's actually interpreted as:
(a = false) or true
This is because =
has a higher precedence when being evaluated.
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
is this not using boolean operators in c++?
EDIT: the function foundWordInBoth is a boolean function and there is
no error with the code.i showed my teacher my code and he said no that way is too easy you
need to use boolean operators, which is why im confused
Your code seems fine to me. Probably your teacher wants you to use the bitwise boolean operators &
and |
instead of the logical operators &&
and ||
.
In that case true & true = 1
, true | false = 1
...
In Java, what are the boolean order of operations?
The Java Tutorials has a list illustrating operator precedence. The equality operators will be evaluated first, then &&
, then ||
. Parentheses will be evaluated before anything else, so adding them can change the order. This is usually pretty much the same from language to language, but it's always a good idea to double check.
It's the small variations in behavior that you're not expecting that can cause you to spend an entire day debugging, so it's a good idea to put the parentheses in place so you're sure what the order of evaluation will be.
Related Topics
Split a Large Dataframe into a List of Data Frames Based on Common Value in Column
Cannot Install R-Forge Package Using Install.Packages
Reorder Levels of a Factor Without Changing Order of Values
Subset/Filter Rows in a Data Frame Based on a Condition in a Column
How to Do Vlookup and Fill Down (Like in Excel) in R
R Reshape Data Frame from Long to Wide Format
Calculate the Mean of Every 13 Rows in Data Frame
Fastest Way to Add Rows For Missing Time Steps
Remove 'A' from Legend When Using Aesthetics and Geom_Text
How to Arrange a Variable List of Plots Using Grid.Arrange
Numbering Rows Within Groups in a Data Frame
Force the Origin to Start At 0
Can Lists Be Created That Name Themselves Based on Input Object Names
Getting the Top Values by Group