Java Reference
In-Depth Information
If you look at the ordering of characters in Appendix 3, you will see that
all
uppercase
letters come before
all
lowercase letters. For example,
'Z'
comes before
'a'
in lexico-
graphic order. So when comparing two strings consisting of a mix of lowercase and upper-
case letters, lexicographic and alphabetic ordering are not the same. However, as shown in
Appendix 3, all the lowercase letters are in alphabetic order. So for any two strings of all
lowercase letters, lexicographic order is the same as ordinary alphabetic order. Similarly, in
the ordering of Appendix 3, all the uppercase letters are in alphabetic order. So for any
two strings of all uppercase letters, lexicographic order is the same as ordinary alphabetic
order. Thus, if you treat all uppercase letters as if they were lowercase, then lexicographic
ordering becomes the same as alphabetic ordering. This is exactly what the method
compareToIgnoreCase
does. Thus, the following produces correct output:
compareTo
IgnoreCase
if
(s1.compareToIgnoreCase(s2) < 0)
System.out.println(
s1 + " precedes " + s2 + " in ALPHABETIC ordering");
else
if
(s1.compareToIgnoreCase(s2) > 0)
System.out.println(
s1 + " follows " + s2 + " in ALPHABETIC ordering");
else
//s1.compareToIgnoreCase(s2) == 0
System.out.println(s1 + " equals " + s2 + " IGNORING CASE");
The above code will compile and produce results no matter what characters are in the
strings
s1
and
s2
. However, alphabetic order and the output only make sense if the
two strings consist entirely of letters.
The program in Display 3.4 illustrates some of the string comparisons we have just
discussed.
Self-Test Exercises
13. Suppose
n1
and
n2
are two
int
variables that have been given values. Write a
Boolean expression that returns
true
if the value of
n1
is greater than or equal to
the value of
n2
; otherwise, it should return
false
.
14. Suppose
n1
and
n2
are two
int
variables that have been given values. Write an
if-else
statement that outputs
"n1"
if
n1
is greater than or equal to
n2
and out-
puts
"n2"
otherwise.
15. Suppose
variable1
and
variable2
are two variables that have been given values.
How do you test whether they are equal when the variables are of type
int
? How
do you test whether they are equal when the variables are of type
String
?
16. Assume that
nextWord
is a
String
variable that has been given a
String
value con-
sisting entirely of letters. Write some Java code that outputs the message
"First
half of the alphabet"
, provided
nextWord
precedes
"N"
in alphabetic ordering.
If
nextWord
does not precede
"N"
in alphabetic ordering, the code should output
"Second half of the alphabet"
. (Note that
"N"
uses double quotes to produce a
String
value, as opposed to using single quotes to produce a
char
value.)