Java Reference
In-Depth Information
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 make sense only 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
that outputs
"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
consisting 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.)