Java Reference
In-Depth Information
} else {
System.out.println("It isn\'t Spring!");
}
This calls the
equals()
method for the enumeration referred to by
season
. This method compares the
value in
season
with the value between the parentheses and results in
true
if they are equal or
false
if they
are unequal. You could use the
equals()
method to compare
season
with another variable of type
Season
,
for example:
Season best = Season.winter; // A new variable initialized to winter
if(season.equals(best)) {
System.out.println("season is the same as best, and is equal to "+ best);
} else {
System.out.println(" season has the value "+season +
" and best has the value " + best);
}
After defining the variable,
best
, you test whether the value of
season
is the same value as
best
. If it
is, the first output statement is executed. If
best
and
season
are not equal, the output statement in the
else
block is executed.
LOGICAL OPERATORS
The tests you have put in the
if
expressions have been relatively simple so far. Real life is typically more
complicated. You often want to combine a number of conditions so that you execute a particular course —
for example, if they are all
true
simultaneously. You can ride the roller coaster if you are older than 12 years
old, taller than 4 feet tall, and shorter than 6 feet. Failure on any count and it's no-go. Sometimes, though,
you may need to test for any one of a number of conditions being
true
— for example, you get a lower price
entry ticket if you are under 16, or over 65.
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
logical AND
conditional AND
&&
logical OR
|
conditional OR
||
exclusive OR (XOR)
^
logical negation (NOT)
!
The AND and OR operators are very simple; the only point of potential confusion is the fact that you
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 dif-
ferent from
&&
and
||
. Let's first consider what each of these is used for in general terms and then look at
how you can use some of them in an example.