Java Reference
In-Depth Information
The following truth table shows that the OR operator evaluates to true except
when both operands are false .
Truth Table for OR ( || )
p
q
p || q
true
true
true
true
false
true
false
true
true
false
false
false
The Java OR operator has a slightly different meaning from the English word “or.”
In English you say, “I'll study tonight or I'll go to a movie.” One or the other will be
true, but not both. The OR operator is more like the English expression “and/or”: If
one or both operands are true , the overall proposition is true .
You generally use logical operators when what you have to say cannot be reduced
to a single test. For example, as we saw in the previous chapter, if you want to do a
particular operation when a number is between 1 and 10, you might say,
if (number >= 1) {
if (number <= 10) {
doSomething();
}
}
But you can say this more easily using logical AND :
if (number >= 1 && number <= 10) {
doSomething();
}
People use the words “and” and “or” all the time, but Java only allows you to use
them in the strict logical sense. Be careful not to write code like the following:
// this does not compile
if (x == 1 || 2 || 3) {
doSomething();
}
In English, we would read this as “ x equals 1 or 2 or 3 ,” which makes sense to us, but
it doesn't make sense to Java. You might also be tempted to write code like the following:
// this does not compile
if (1 <= x <= 10) {
doSomethingElse();
}
 
Search WWH ::




Custom Search