Java Reference
In-Depth Information
You can deal with both of these cases, and more, using logical operators to combine several expressions
that have a value true or false . Because they operate on boolean values they are also referred to as
boolean operators . There are five logical operators that operate on boolean values:
Symbol
Long name
&
logical AND
&&
conditional AND
|
logical OR
||
conditional OR
!
logical negation (NOT)
These are very simple, the only point of potential confusion being the fact that we have the choice of
two operators for each of AND and OR. The extra operators are the bitwise & and | from the previous
chapter that you can also apply to boolean values where they have an effect that is subtly different
from && and || . We'll first consider what each of these are used for in general terms, then we'll look at
how we can use them in an example.
Boolean AND Operations
You can use either AND operator, && or & , where you have two logical expressions that must both be true
for the result to be true - that is, you want to be rich and healthy. Either operator will produce the same
result from the logical expression. We will come back to how they are different in a moment. First, let's
explore how they are used. All of the following discussion applies equally well to & as well as && .
Let's see how logical operators can simplify the last example. You could use the && operator if you were
testing a variable of type char to determine whether it contained an uppercase letter or not. The value
being tested must be both greater than or equal to ' A ' AND less than or equal to ' Z '. Both conditions
must be true for the value to be a capital letter. Taking the example from our previous program, with a
value stored in a char variable symbol , we could implement the test for an uppercase letter in a single
if by using the && operator:
if(symbol >= 'A' && symbol <= 'Z')
System.out.println("You have the capital letter " + symbol);
If you take a look at the precedence table back in Chapter 2, you will see that the relational operators
will be executed before the && operator, so no parentheses are necessary. Here, the output statement
will be executed only if both of the conditions combined by the operator && are true . However, as we
have said before, it is a good idea to add parentheses if they make the code easier to read. It also helps
to avoid mistakes.
In fact, the result of an && operation is very simple. It is true only if both operands are true ,
otherwise the result is false .
We can now rewrite the set of if s from the last example.
Search WWH ::




Custom Search