go to previous page   go to home page   go to next page

Answer:

"turtle" .compareTo ("turtledove") negative
"polarbear" .compareTo ("polarbear") zero
"freezing point" .compareTo ("freezing") positive
"Power" .compareTo ("power") negative
"FORTRAN" .compareTo ("fortran") negative

Collating Sequence

The alphabet that Java uses in comparing characters is called a collating sequence. All characters are placed into this sequence, so any two characters can be compared. Here is the part of the sequence that includes the most common characters:


sp ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
`  a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~

Characters are listed in increasing value, so

A < K
0 < Z
Z < a
% < + 
@ < {
z < ~

The first character listed 'sp' stands for the single space character. For example,

" hello".compareTo("hello")

returns a negative value.

Most of the time you don't need these details. But sometimes you do, so it is nice to know that they exist. The fact that space comes before nearly all other characters is sometimes useful to explain unexpected program behavior.


QUESTION 11:

More practice. Compare digit-containing strings like "23.5" using character-by-character string comparison, not arithmetic comparison.

ComparisonZero, Negative, or Positive
" 9999" .compareTo ("023")
"(rat)" .compareTo ("[cat]")
"23.5" .compareTo ("23,7")
"More Cheese?" .compareTo ("More Cheese!")
"cobol" .compareTo ("cobalt")