Java Reference
In-Depth Information
You have four
if
statements altogether. The first
if
tests whether
symbol
is '
A
' or greater. If it is, it could
be a capital letter, a small letter, or possibly something else. But if it isn't, it is not a letter at all, so the
else
for this
if
statement (toward the end of the program) produces a message to that effect.
The nested
if
statement, which is executed if
symbol
is '
A
' or greater, tests whether it is '
Z
' or less. If
it is, then
symbol
definitely contains a capital letter, and the appropriate message is displayed. If it isn't
then it may be a small letter, so another
if
statement is nested within the
else
clause of the first nested
if
to test for this possibility.
The
if
statement in the
else
clause tests for
symbol
being greater than '
a
'. If it isn't, you know that
symbol
is not a letter, and a message is displayed. If it is, another
if
checks whether
symbol
is '
z
' or
less. If it is you have a small letter, and if not you don't have a letter at all.
You have to run the example a few times to get all the possible messages to come up. They all will —
eventually.
After having carefully crafted our convoluted and cumbersome condition checking, I can now reveal that
there is a much easier way to achieve the same result. You'll see that in the section “Logical Operators”
that follows immediately after a brief word on working with enumeration values.
Comparing Enumeration Values
You can't compare variables of an enumeration type using the comparison operators but you can compare
them using a method that every enumeration object provides. Suppose you define an enumeration type as:
enum Season { spring, summer, fall, winter }
You can now define and initialize a variable of type
Season
with the following statement:
Season season = Season.summer;
If you later want to check what the
season
variable currently holds, you could write:
if(season.equals(Season.spring)) {
System.out.println("Spring has sprung, the grass is riz.");