Java Reference
In-Depth Information
Display 1.4 Some Methods in the Class String (part 4 of 4)
int compareTo( A_String )
Compares the calling object string and the string argument to see which comes first in the lexico-
graphic ordering. Lexicographic order is the same as alphabetical order but with the characters
ordered as in Appendix 3. Note that in Appendix 3 all the uppercase letters are in regular alphabetical
order and all the lowercase letters are in alphabetical order, but all the uppercase letters precede all
the lowercase letters. So, lexicographic ordering is the same as alphabetical ordering provided both
strings are either all uppercase letters or both strings are all lowercase letters. If the calling string is
first, it returns a negative value. If the two strings are equal, it returns zero. If the argument is first, it
returns a positive number.
EXAMPLE
After program executes String entry = "adventure";
entry.compareTo("zoo") returns a negative number,
entry.compareTo("adventure") returns 0 , and
entry.compareTo("above") returns a positive number.
int compareToIgnoreCase( A_String )
Compares the calling object string and the string argument to see which comes first in the lexico-
graphic ordering, treating uppercase and lowercase letters as being the same. (To be precise, all
uppercase letters are treated as if they were their lowercase versions in doing the comparison.) Thus,
if both strings consist entirely of letters, the comparison is for ordinary alphabetical order. If the call-
ing string is first, it returns a negative value. If the two strings are equal ignoring case, it returns zero.
If the argument is first, it returns a positive number.
EXAMPLE
After program executes String entry = "adventure";
entry.compareToIgnoreCase("Zoo") returns a negative number,
entry.compareToIgnoreCase("Adventure") returns 0 , and
"Zoo".compareToIgnoreCase(entry) returns a positive number.
Some methods for the class String depend on counting positions in the string. Posi-
tions are counted starting with 0 not with 1. So, in the string "Surf time" , 'S' is in
position 0 , 'u' is in position 1 , and so forth. A position is usually referred to as an index .
So, it would be preferable to say: 'S' is at index 0 , 'u' is at index 1 , and so forth.
The method indexOf can be used to find the index of a substring of the calling
objects. For example, consider
position
index
String phrase = "Java is fun.";
After this declaration, the invocation phrase.indexOf("is") will return 5 because the
'i' of "is" is at index 5 . (Remember, the first index is 0 , not 1 .) This is illustrated in
Display 1.5.
 
Search WWH ::




Custom Search